Newbie question regarding string.split()

Grant Edwards grante at visi.com
Fri Apr 20 21:08:09 CEST 2007


On 2007-04-20, kevinliu23 <kevinliu23 at gmail.com> wrote:
> Hey guys,
>
> So I have a question regarding the split() function in the string
> module. Let's say I have an string...
>
> 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?

The presense of a delimiter indicates that there is a field
both before and after the delimiter. If it didn't work that
way, then you'd get the same results for 

  input = "2b 3 4bx 5b 2c 4a 5a 6"

as you would for 

  input = "b 3 4bx 5b 2c 4a 5a 6"

you would get the same results for

  input = "2222b22222"

as you would for
  
  intput = "b"
  
> What can I do so that the first element is not an empty
> string? but the 'b34bx5b' string as I expected?

   projectOptions = (input.replace(" ", "")).split('2')
   if projectOptions[0] == '':
      del projectOptions[0]
   print projectOptions

-- 
Grant Edwards                   grante             Yow! I feel like a wet
                                  at               parking meter on Darvon!
                               visi.com            



More information about the Python-list mailing list