views:

246

answers:

7

It's too hot & I'm probably being retarded.

>>> "/1/2/3/".split("/")
['', '1', '2', '3','']

Whats with the empty elements at the start and end?

Edit: Thanks all, im putting this down to heat induced brain failure. The docs aren't quite the clearest though, from http://docs.python.org/library/stdtypes.html

"Return a list of the words in the string, using sep as the delimiter string"

Is there a word before the first, or after the last "/"?

+17  A: 

Compare with:

"1/2/3".split("/")

Empty elements are still elements.

You could use strip('/') to trim the delimiter from the beginning/end of your string.

ceejayoz
Summarizing: `"/1/2/3/".strip("/").split("/")`. Easiest way to fix it.
bradlis7
+2  A: 

Slashes are separators, so there are empty elements before the first and after the last.

Jim Garrison
Just adding: that's to say, each separator has something before and something after, including the first and last separators
Diego Pereyra
+1  A: 

you're splitting on /. You have 4 /, so, the list returned will have 5 elements.

nosklo
+1 the counting makes it way more intuitive
jdizzle
Except they're forward slashes!
asmeurer
+4  A: 

As JLWarlow says, you have an extra '/' in the string. Here's another example:

>>> "//2//3".split('/')
['', '', '2', '', '3']
Daenyth
A: 

That is exactly what I would expect, but we are all different :)

What would you expect from: : "1,,2,3".split(",") ?

thomask
['1','','2','3']
JLWarlow
A: 

You can use strip() to get rid of the leading and trailing fields... Then call split() as before.

Platinum Azure
Except in python it is `strip()`, not `trim()` :)
bradlis7
Damn it, I even knew that. How I mistyped that I'll never know. Fixing shortly.
Platinum Azure
A: 
[x for x in "//1///2/3///".split("/") if x != ""]
mykhal
err, now I see Brian posted almost exactly the same solution on the comments before..
mykhal
you could just check with `if x`
SilentGhost