newb question on strings

shandy.b at gmail.com shandy.b at gmail.com
Tue Jun 24 17:04:04 EDT 2008


Are you trying to escape for a regular expression?

Just do re.escape().

>>> print re.escape('Happy')
Happy
>>> print re.escape("Frank's Diner")
Frank\'s\ Diner

If you're escaping for URLs, there's urllib2.quote(), for a command
line, use subprocess.list2cmdline.

Generally, the module that consumes the string should provide a
function like escape().


On Jun 24, 1:27 pm, regex_jedi <kim.gen... at gmail.com> wrote:
> ok, I have looked a lot of places, and can't seem to get a clear
> answer...
>
> I have a string called
>    each_theme
>
> Some values of the string may contain a single quote as in -
>    Happy
>    Sad
>    Nice
>    Frank's Laundry
>    Explosion
>
> Notice that the 4th value has a single quote in it. Well, I need to
> make sure that the single quote is escaped before handing it off for
> further processing to a class I later call for some other processing.
>
> So I thought, no big deal, I should be able to find a way to escape
> the single quote on the string.  I am a perl and PHP guy, so I do a
> lot of regex stuff.  I did a quick search and found someone had said
> to use this re.sub function, so I tried.  But the following doesn't
> work. To be honest, I am a little lost with all the modules and
> classes required to do simple math or string functions in Python.
> None of it seems built it in.. its all import modules...  Here is what
> I am trying...
>
>         # escape single quotes in theme name
>         re.sub('''(['"])''', r'\\\1', each_theme)
>
> you python masters... show me the way please...
>
> thanks
> regex_jedi




More information about the Python-list mailing list