Python tip 25: split and partition string methods
The split()
method splits a string based on the given substring and returns a list
. By default, whitespace is used for splitting and empty elements are discarded.
>>> greeting = ' \t\r\n have a nice \r\v\t day \f\v\r\t\n '
>>> greeting.split()
['have', 'a', 'nice', 'day']
You can split the input based on a specific string literal by passing it as an argument. Here are some examples:
>>> creatures = 'dragon][unicorn][centaur'
>>> creatures.split('][')
['dragon', 'unicorn', 'centaur']
# empty elements will be preserved in this case
>>> ':car::jeep::'.split(':')
['', 'car', '', 'jeep', '', '']
The maxsplit
argument allows you to restrict the number of times the input string should be split. Use rsplit()
if you want to split from right to left.
# split once
>>> 'apple-grape-mango-fig'.split('-', maxsplit=1)
['apple', 'grape-mango-fig']
# match the rightmost occurrence
>>> 'apple-grape-mango-fig'.rsplit('-', maxsplit=1)
['apple-grape-mango', 'fig']
>>> 'apple-grape-mango-fig'.rsplit('-', maxsplit=2)
['apple-grape', 'mango', 'fig']
The partition()
method will give a tuple
of three elements — portion before the leftmost match, the separator itself and the portion after the split. You can use rpartition()
to match the rightmost occurrence of the separator.
>>> marks = 'maths:85'
>>> marks.partition(':')
('maths', ':', '85')
# last two elements will be empty if there is no match
>>> marks.partition('=')
('maths:85', '', '')
# match the rightmost occurrence
>>> creatures = 'dragon][unicorn][centaur'
>>> creatures.rpartition('][')
('dragon][unicorn', '][', 'centaur')
See my Understanding Python re(gex)? ebook to learn about string splitting with regular expressions.
Video demo:
See also my 100 Page Python Intro ebook.