Channel72
Channel72

Reputation: 24719

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?

Upvotes: 3

Views: 1547

Answers (4)

Andrew Clark
Andrew Clark

Reputation: 208485

In addition to the other answers, one way to prevent empty strings at the beginning and end of your list is to strip off leading and trailing / characters:

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

Note that you would still get an empty string if there were consecutive / characters in the middle of the string.

Upvotes: 1

rjralgar
rjralgar

Reputation: 153

Contrast these examples:

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

vs

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

having an extra '' in your list means you can distinguish between whether there was a / at the start or your string or not

Upvotes: 2

Adam Wagner
Adam Wagner

Reputation: 16107

To add to David's answer... split seperates sections of a string by a given delimiter. an empty string must be considered a valid section, otherwise, splitting cases like this would also be problematic:

'//'.split('/')

What else should this return, other than ['', '', '']?

Upvotes: 4

David Wolever
David Wolever

Reputation: 154504

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']

Upvotes: 5

Related Questions