Source
Adapted from my own handwritten and hand-typed notes from Year 1 to Year 3 of my EEE degree
A str is a sequence of characters. All string operations are case sensitive.
Indexing
Python uses zero-based indexing. A negative index counts backwards from the last character.
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
s | m | o | z | z | a | r | e | L | l | a |
| negative | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
Common Methods
| Operation | Example | Result | Returns |
|---|---|---|---|
concatenate + | 'Hello' + ' World' | 'Hello World' | str |
length len | len('Hello') | 5 | int |
| count substring | 'Hello World. Hello friends.'.count('Hello') | 2 | int |
locate index | s.index('z'), s.index('l'), s.index('are') | 2, 8, 4 | int |
| upper / lower | 'Hello World'.upper() | 'HELLO WORLD' | str |
| replace | 'Hello Ben!'.replace('Ben', 'Amy') | 'Hello Amy!' | str |
| split | 'Hello, World!'.split(',') | ['Hello', ' World!'] | list |
Notes on these methods:
indexreturns the position of the first letter of the first occurrence, and'l'and'L'count as different letterssplit()with no argument splits on whitespacesplitis useful for reading CSV (comma separated values) files line by line- if the separator sits at the very start,
splitgives an empty string as the first item
Slicing
Syntax s[start:stop:step] takes characters from start up to but not including stop, picking one every step. A negative step slices in reverse.
s = 'mozzareLla'
s[2] # 'z'
s[1:9] # 'ozzareLl' (stop index 9 not included)
s[2:9:3] # 'zrl'
s[2:-3] # 'zzare'
s[-1:1:-3] # 'aez'Shorthand Slices
Leaving out a value uses the default, and the position relative to : says which value it is:
s[::-1] # 'alLerazzom' all characters, reversed
s[-3:] # 'Lla' last three characters
s[:-2] # 'mozzareL' all except last two
s[1::-1] # 'om' first two characters, reversed
s[-1:-3:-1] # 'al' last two characters, reversedThe same slicing rules carry over to Python Lists.