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.

index0123456789
smozzareLla
negative-10-9-8-7-6-5-4-3-2-1

Common Methods

OperationExampleResultReturns
concatenate +'Hello' + ' World''Hello World'str
length lenlen('Hello')5int
count substring'Hello World. Hello friends.'.count('Hello')2int
locate indexs.index('z'), s.index('l'), s.index('are')2, 8, 4int
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:

  • index returns the position of the first letter of the first occurrence, and 'l' and 'L' count as different letters
  • split() with no argument splits on whitespace
  • split is useful for reading CSV (comma separated values) files line by line
  • if the separator sits at the very start, split gives 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, reversed

The same slicing rules carry over to Python Lists.