[Tutor] str.split and quotes
C Smith
smichr at hotmail.com
Wed Apr 6 18:03:55 CEST 2005
> I wish it would leave the stuff in quotes in tact:
>
If you first split on your delimiter (which must have a matching one)
you will obtain a list in which every odd position contains a string
that was quoted. Step through the result and split the ones that are
not quoted ones but don't do anything to the quoted ones.
###
s='"Hi" there "Python Tutors" please help me'
delim='"'
# check for matching quotes
if s.count(delim)%2<>0:
print 'Unmatched delimiters in string'
assert s.count(delim)%2==0
# split it
s=s.split(delim)
# remove elements 1 at a time, putting result to end of list;
# when you're done, the original list has been destroyed and
# the correct list is in its place
for i in range(len(s)):
si=s.pop(0) #pop off the next one from the list
if i%2==0:
s.extend(si.split())
else:
s.append(si)
print s
###
OUTPUT: ['Hi', 'there', 'Python Tutors', 'please', 'help', 'me']
/c
More information about the Tutor
mailing list