string.split bug?

Peter Otten __peter__ at web.de
Wed Feb 25 03:05:05 EST 2004


MetalOne wrote:

> string.split("") ==> []
> string.split("",",") ==> ['']
> 
> I did not expect these to have different outputs.
> 
> I have a string with comma delimited numbers.
> There can be zero or more numbers in the string
> s = "0x41, 0x42"
> 
> I wanted to do
> numbers = map(lambda x: int(x,16), string.split(s,","))
> 
> However, when there are no numbers, this generates an error.

It's not a bug, it's a feature. The same question was asked on python-dev
recently, and it turned out that str.split() and str.split(separator) are
intended to work differently. 

A slightly modernized variant of your example could then be:

>>> def numbers(s, sep=None):
...     return [int(x, 16) for x in s.split(sep) if x]
...
>>> numbers("aa bb cc\n")
[170, 187, 204]
>>> numbers("aa,bb,cc", ",")
[170, 187, 204]
>>> numbers("", ",")
[]

Peter




More information about the Python-list mailing list