Python strings are immutable sequences, meaning that the characters they contain cannot be changed in place.
Python strings are Python sequences.
The sequence operations introduced here will work the same on other sequence types, such as lists and tuples.
The following table lists common string literals and operations.
Empty strings are written as a pair of quotation marks (single or double) with nothing in between.
Operation | Interpretation |
---|---|
S = '' | Empty string |
S = "test's" | Double quotes, same as single |
S = 's\n \ta\x00m' | Escape sequences |
S = """...multiline ...""" | Triple-quoted block strings |
S = r'\temp\test' | Raw strings (no escapes) |
B = b'sp\xc4m' | Byte strings in 2.6, 2.7, and 3.X |
U = u'sp\u00c4m' | Unicode strings in 2.X and 3.3+ |
S1 + S2 | Concatenate, repeat |
S * 3 | Concatenate, repeat |
S[i] | Index |
S[i:j] | slice |
len(S) | length |
"a %s test" % kind | String formatting expression |
"a {0} test".format(kind) | String formatting method in 2.6, 2.7, and 3.X |
S.find('pa') | String methods: search, |
S.rstrip() | remove whitespace, |
S.replace('pa', 'xx') | replacement, |
S.split(',') | split on delimiter, |
S.isdigit() | content test, |
S.lower() | case conversion, |
S.endswith('test') | end test, |
'test'.join(strlist) | delimiter join, |
S.encode('latin-1') | Unicode encoding, |
B.decode('utf8') | Unicode decoding, etc. |
for x in S: print(x) | Iteration, membership |
'test' in S | Iteration, membership |
[c * 2 for c in S] | Iteration, membership |
map(ord, S) | Iteration, membership |
re.match('sp(.*)am', line) | Pattern matching: library module |