57
132
Chapter 6
string, gets passed a list of strings, and returns a string. The returned string
is the concatenation of each string in the passed-in list. For example, enter
the following into the interactive shell:
>>> ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'
Notice that the string
join()
calls on is inserted between each string
of the list argument. For example, when
join(['cats', 'rats', 'bats'])
is
called on the
', '
string, the returned string is 'cats, rats, bats'.
Remember that
join()
is called on a string value and is passed a list
value. (It’s easy to accidentally call it the other way around.) The
split()
method does the opposite: It’s called on a string value and returns a list of
strings. Enter the following into the interactive shell:
>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
By default, the string
'My name is Simon'
is split wherever whitespace char-
acters such as the space, tab, or newline characters are found. These white-
space characters are not included in the strings in the returned list. You can
pass a delimiter string to the
split()
method to specify a different string to
split upon. For example, enter the following into the interactive shell:
>>> 'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
>>> 'My name is Simon'.split('m')
['My na', 'e is Si', 'on']
A common use of
split()
is to split a multiline string along the newline
characters. Enter the following into the interactive shell:
>>> spam = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment".
Please do not drink it.
Sincerely,
Bob'''
>>> spam.split('\n')
['Dear Alice,', 'How have you been? I am fine.', 'There is a container in the
fridge', 'that is labeled "Milk Experiment".', '', 'Please do not drink it.',
'Sincerely,', 'Bob']