[Tutor] str.split and quotes
Kent Johnson
kent37 at tds.net
Wed Apr 6 13:44:48 CEST 2005
Marilyn Davis wrote:
> Hi Tutors,
>
> I need a little help with this, if anyone has the time and inclination:
>
>
>>>>s = 'Hi "Python Tutors" please help'
>>>>s.split()
>
> ['Hi', '"Python', 'Tutors"', 'please', 'help']
>
>
> I wish it would leave the stuff in quotes in tact:
>
> ['Hi', '"Python Tutors"', 'please', 'help']
You can do this easily with the csv module. The only complication is that the string has to be
wrapped in a StringIO to turn it into a file-like object. If your strings are actually coming from a
file then the wrapping isn't needed, you can pass the file directly to csv.reader().
>>> import StringIO, csv
>>> s = 'Hi "Python Tutors" please help'
>>> input = StringIO.StringIO(s)
>>> csv.reader(input, delimiter=' ').next()
['Hi', 'Python Tutors', 'please', 'help']
Oops, that isn't actually what you asked for, it strips the quotes. Oh well.
Kent
More information about the Tutor
mailing list