[Tutor] str.split and quotes

Liam Clarke cyresse at gmail.com
Wed Apr 6 08:05:36 CEST 2005


Hi Marilyn, 

Before you get numerous suggestions to use regexes (which was my first idea), 
you could use the split method to do it - 

>>> q = 'Hi "Python Tutors" please help'
>>> w = q.split('\"')
>>> print w
['Hi ', 'Python Tutors', ' please help']

I'm splitting using a double speech mark as the argument, which I've expressed 
as \" which is a hangover from regexes.

But, there are limitations to that -

>>> x = 'Hi "Python Tutors" how " are you?'
>>> print x.split('\"')
['Hi ', 'Python Tutors', ' how ', ' are you?']

It won't differentiate between an item between two speech marks, or one.

So, a regex method could be - 

>>> import re 
>>> j = re.compile('\"(.*?)\"', re.IGNORECASE)
>>> q = 'Hi "Python Tutors" please help'
>>> j.findall(q)
['Python Tutors']
>>> j.findall(x)
['Python Tutors']
>>> w = ' he "Foo foo" bob marley " fee fee " '
>>> j.findall(w)
['Foo foo', ' fee fee ']

I recommend this http://www.amk.ca/python/howto/regex/ 
and python2x/tools/scripts/redemo.py to learn how to use regexes well.


Regards, 

Liam Clarke




On Apr 6, 2005 5:19 PM, Marilyn Davis <marilyn at deliberate.com> 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']
> 
> Any suggestions?
> 
> Thank you.
> 
> Marilyn Davis
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


More information about the Tutor mailing list