How can we get to the end of a quote inside a string

Wojtek Walczak gminick at bzt.bzt
Sun Aug 31 13:20:43 EDT 2008


On Sun, 31 Aug 2008 07:29:26 -0700 (PDT), rajmohan.h at gmail.com wrote:

>     Suppose I have a string which contains quotes inside quotes -
> single and double quotes interchangeably -
>  s = "a1' b1 " c1' d1 ' c2" b2 'a2"

>>> s = "a1' b1 " c1' d1 ' c2" b2 'a2"
  File "<stdin>", line 1
    s = "a1' b1 " c1' d1 ' c2" b2 'a2"
                   ^
SyntaxError: invalid syntax
>>>

Writing a small parser for your needs shouldn't be that hard.
To some extent you can use regular expressions:

>>> re.findall(re.compile("\".*?\""), s)
['" c1\' d1 \' c2"']
>>> re.findall(re.compile("\'.*?\'"), s)
['\' b1 " c1\'', '\' c2" b2 \'']
>>>

but it won't work in all cases. You can read more here:
http://www.gnosis.cx/TPiP/

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/



More information about the Python-list mailing list