Outline for February 1
Reading: text, §5.2–5.3
Due: Homework 2, due on February 4 at 11:55pm — note extension
- String methods: find characters and substrings (return position or cause exception) cstrfind.py]
- S.find(s) — Return the index of the first occurrence of s in S; −1 if s not in S
- S.index(s) — Return the index of the first occurrence of s in S; ValueError exception if s not in S
- S.rfind(s) — Return the index of the last occurrence of s in S; −1 if s not in S
- S.rindex(s) — Return the index of the last occurrence of s in S; ValueError exception if s not in S
- String methods: miscellaneous [strmisc.py]
- S.count(s) — Return the number of times s occurs in S
- S.startswith(s) — True if S starts with s
- S.endswith(s) — True if S ends with s
- S.replace(s,t) — Replace all occurrences of s with t in S
- Lists
- Sequence of values (ints, floats, strings, other lists, etc.)
- Denoted by square brackets [ ] with values separated by commas
- Lists are mutable
- How to create a list
- Program to print words in a line [lines.py]
- Program to compute some statistics [addup.py]
- What you can do with lists
- Check membership: in, not in
- +: concatenation
- *: repetition
- list[a:b]: slice list from a to b−1
- del list[i]: delete element list[i]; i can be a slice
- Objects, references, aliasing
- For strings, one copy: assume a = "banana"
- After b = a or b = a[:], then a is b is True
- For lists, multiple copies: assume A = [ 1, 2, 3 ]
- After B = A, then A is B is True
- After B = A[:], then A is B is False
- list(enumerate(L)) produces pairs (index, list element)
- Lists as parameters: can change list elements in function and they are changed in caller [args2.py]
- Add elements to, remove elements: L.append(x), L.extend(ls), L.insert(i, x), L.pop(), L.remove(x)
- Element ordering: L.reverse(), L.sort()
- Other: L.count(x), L.index(x)
- Tuples
- Used to group data
- Like lists, but immutable