Newbie question regarding string.split()

Steve Holden steve at holdenweb.com
Fri Apr 20 15:13:26 EDT 2007


kevinliu23 wrote:
> Hey guys,
> 
> So I have a question regarding the split() function in the string
> module. Let's say I have an string...
> 
First of all, the string module is pretty much deprecated nowadays. What 
you are actually using, the .split() method of a string, is the 
preferred way to do it. If you are importing string, don't bother!


> input = "2b 3 4bx 5b 2c 4a 5a 6"
> projectOptions = (input.replace(" ", "")).split('2')
> print projectOptions
> 
> ['', 'b34bx5b', 'c4a5a6']
> 
> My question is, why is the first element of projectOptions an empty
> string? What can I do so that the first element is not an empty
> string? but the 'b34bx5b' string as I expected?
> 
Because .split() returns a list of the strings surrounding each 
occurrence of the split argument. Because the string begins with the 
split argument it returns an empty string as the first element (since 
the assumption is you are interested in both sides of the separator).

You can easily throw the first element away:

    del projectOptions [0]

for example, or

    projectOptions = projectOptions[1:]

But what do you want to do if the string *doesn't* begin with a 2?

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Recent Ramblings       http://holdenweb.blogspot.com




More information about the Python-list mailing list