Python Glossary Русский

all Python 3Strings (str)function

str.split

splitting

Split the string by a separator into a list; with no argument, split on any whitespace.

Syntax

s.split(sep=None, maxsplit=-1)

The two modes differ exactly at the edges and on repeats: split() with no argument collapses runs of whitespace and ignores leading/trailing ones, while split(' ') faithfully returns an empty string for every extra space. Hence the classic empty-input trap — ''.split() gives an empty list, but ''.split(',') gives a list holding one empty string, and a length check breaks. An empty separator is rejected with ValueError, not treated as per-character splitting.

Examples

print('a,b,c'.split(','))   # → ['a', 'b', 'c']
print('a  b   c'.split())   # → ['a', 'b', 'c']
print('a,b,c'.split(',', 1))  # → ['a', 'b,c']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy