-
If is a piece of text PRESENT in the string → sub in s, a bool; never s.find(sub) as a truth test, since position 0 is false
Example: 'an' in 'banana' is True
-
If WHERE a piece of text is → s.find(sub), then if pos == -1 before any use of pos as an index
Example: 'banana'.find('an') is 1, 'banana'.find('x') is -1
s.index(sub) raises instead of returning -1: choose it only when absence is a bug
-
If HOW MANY times a piece of text occurs → s.count(sub) for a substring; a loop with c in 'aeiou' for a set of characters
Example: 'banana'.count('an') is 2, vowels of 'banana' are 3
-
If TAKE a part of the string: first n, last n, a window at i → a slice, s[:n], s[-n:], s[i:i+n]; an index only for one character
Example: 'BANANA'[1:1+3] is 'ANA', 'BANANA'[-2:] is 'NA'
-
If CHANGE a part of the string → build a new one: 'J' + s[1:], s.replace(old, new), or the loop with an accumulator; then name the result
Example: 'B' + 'banana'[1:] is 'Banana'
-
If BREAK a line into fields, or GLUE fields into a line → s.split(sep) keeps empty fields, s.split() collapses whitespace; sep.join(list_of_strings) for the way back
Example: 'a,,b'.split(',') has 3 pieces, ' a b '.split() has 2
-
If COMPARE two strings, or CLEAN one before comparing → strip() and lower() both sides, then ==; int() both sides when the strings hold numbers
Example: ' Ana '.strip().lower() == 'ana'; int('10') < int('9') is False
-
If SHIFT or NUMBER a letter → ord(c) - ord('a') for the position 0 to 25, arithmetic, % 26, then chr back
Example: shifting 'x' by 3 gives 'a', since (23 + 3) % 26 is 0
Every branch ends with a value. If the value has no name and is not returned, the branch was taken for nothing: that is the fil of the chapter, and it is where the marks go.