Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: first character when splitting

I just noticed the split method produces an empty string in the result list if the first character is a delimiter string.

Example:

>>> s = '/foo/bar/blarg'
>>> s.split('/')
['', 'foo', 'bar', 'blarg']

I expected this to produce:

['foo', 'bar', 'blarg']

Is there some reason why this is desirable behavior, or is this simply a bug?

like image 886
Channel72 Avatar asked May 07 '26 12:05

Channel72


1 Answers

This is the desired behaviour, because otherwise it would be impossible to distinguish between "/foo".split("/") and "foo".split("/').

When I'm using split and know that I don't want possibly empty strings, I'll use filter(None, foo.split("/")) to remove them:

>>> filter(None, "/foo//bar".split("/"))
['foo', 'bar']
like image 110
David Wolever Avatar answered May 09 '26 02:05

David Wolever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!