Why are empty strings returned in split() results?

orokusaki picture orokusaki · Feb 4, 2010 · Viewed 68.7k times · Source

What is the point of '/segment/segment/'.split('/') returning ['', 'segment', 'segment', '']?

Notice the empty elements. If you're splitting on a delimiter that happens to be at position one and at the very end of a string, what extra value does it give you to have the empty string returned from each end?

Answer

John La Rooy picture John La Rooy · Feb 4, 2010

str.split complements str.join, so

"/".join(['', 'segment', 'segment', ''])

gets you back the original string.

If the empty strings were not there, the first and last '/' would be missing after the join()