string.split bug?

M

MetalOne

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.
 
P

Peter Otten

MetalOne said:
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:
.... 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
 
E

Erik Max Francis

MetalOne said:
string.split("") ==> []
string.split("",",") ==> ['']

I did not expect these to have different outputs.

S.split(None) is a special case which keys off of all whitespace, not
just a single delimiter string. So when presented with an input string
that contains nothing but whitespace, it strips everything and doesn't
find any tokens at all.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top