Behaviour of str.split

David Fraser davidf at sjsoft.com
Wed Apr 20 04:55:18 EDT 2005


Greg Ewing wrote:
> Will McGugan wrote:
> 
>> Hi,
>>
>> I'm curious about the behaviour of the str.split() when applied to 
>> empty strings.
>>
>> "".split() returns an empty list, however..
>>
>> "".split("*") returns a list containing one empty string.
> 
> 
> Both of these make sense as limiting cases.
> 
> Consider
> 
>  >>> "a b c".split()
> ['a', 'b', 'c']
>  >>> "a b".split()
> ['a', 'b']
>  >>> "a".split()
> ['a']
>  >>> "".split()
> []
> 
> and
> 
>  >>> "**".split("*")
> ['', '', '']
>  >>> "*".split("*")
> ['', '']
>  >>> "".split("*")
> ['']
> 
> The split() method is really doing two somewhat different things
> depending on whether it is given an argument, and the end-cases
> come out differently.
> 
You don't really explain *why* they make sense as limiting cases, as 
your examples are quite different.

Consider
 >>> "a*b*c".split("*")
['a', 'b', 'c']
 >>> "a*b".split("*")
['a', 'b']
 >>> "a".split("*")
['a']
 >>> "".split("*")
['']

Now how is this logical when compared with split() above?

David



More information about the Python-list mailing list