String split

Peter Otten __peter__ at web.de
Tue Mar 28 16:59:32 CEST 2006


Michele Petrazzo wrote:

> Hello ng,
> I don't understand why split (string split) doesn't work with the same
> method if I can't pass values or if I pass a whitespace value:
> 
>>>> "".split()
> []
>>>> "".split(" ")
> ['']
> 
> But into the doc I see:
> """ If sep is not specified or is None, any whitespace string is a
> separator.
> """

The documentation for Python 2.4 has a better explanation.

"""
split([sep [,maxsplit]])

Return a list of the words in the string, using sep as the delimiter string.
If maxsplit is given, at most maxsplit splits are done. (thus, the list
will have at most maxsplit+1 elements). If maxsplit is not specified, then
there is no limit on the number of splits (all possible splits are made).
Consecutive delimiters are not grouped together and are deemed to delimit
empty strings (for example, "'1,,2'.split(',')"returns "['1', '', '2']").
The sep argument may consist of multiple characters (for example, "'1, 2,
3'.split(', ')" returns "['1', '2', '3']"). Splitting an empty string with
a specified separator returns "['']". 

If sep is not specified or is None, a different splitting algorithm is
applied. First, whitespace characters (spaces, tabs, newlines, returns, and
formfeeds) are stripped from both ends. Then, words are separated by
arbitrary length strings of whitespace characters. Consecutive whitespace
delimiters are treated as a single delimiter ("'1 2 3'.split()" returns
"['1', '2', '3']"). Splitting an empty string or a string consisting of
just whitespace returns an empty list. 
"""
Quoted after http://docs.python.org/lib/string-methods.html#l2h-202.

Peter



More information about the Python-list mailing list