[Tutor] parsing a string

TJ tgrimes at teleport.com
Sun Oct 10 21:18:43 CEST 2004


>Suppose I have a string that looks like this:
>
>1 1997 2 "Henrik Larsson"
>
>I want to convert the string to a list, with four members. Is there 
>an easy way to do this (the hard way would be to find all quotes, 
>save to a separate string the area between the quotes, remove this 
>part from the original string, use string.split, and put the string 
>back together.
>

Another way to do this for the string format you specify is to remove 
the double quotes and then only split the first 3 items.

>>>  st = '1 1997 2 "Henrik Larsson"'
>>>  st = st.replace('"', '')
>>>  st.split(None, 3)
['1', '1997', '2', 'Henrik Larsson']


TJ


More information about the Tutor mailing list