Strings in Python

Notes on strings in Python.

Background

Strings are an immutable sequence type.

Strings can not be modified using operations for mutable sequence types such as [], insert(), or append(). Any operation that appears to change a string actually creates a new copy of the string.

Concatenation

Strings can be concatenated using sequence operator +, but this is ineficcient (see Joel Spolksy’s article and the Wiki on Schlemiel the Painter). Instead, concatenate strings using string.join().

Using join() requires:

  • a separator in string form (can be an empty string)
  • the strings to concatenate in something iterable

It is used as follows:

separator.join(iterable)

For example,

>>> ''.join(['one', 'two'])
onetwo

>>> '|'.join(('one', 'two'))
one|two

Useful Methods

See all string methods

Further Reading

Python docs: