escape sequences and string comparisons

Remco Gerlich scarblac at pino.selwerd.nl
Mon Jan 8 08:20:05 EST 2001


jkndeja at my-deja.com <jkndeja at my-deja.com> wrote in comp.lang.python:
> Since re.escape() simply uses the criterion of 'non-alphanumeric
> character' to determine whether to escape a character, is there an
> alternative function to 'escape only characters used in string literal
> escapes', am I on my own, or am I missing something?

Simply using repr (or `` backquotes) gives the string as a string literal,
with the necessary things escaped. The only thing is that if there are '
quotes in the string, they aren't escaped, but instead "" quotes are used
to surround the string (and vice versa).

>>> x = '\\'
>>> len(x)
1
>>> print repr(x)
'\\'
>>> x = "'"
>>> print repr(x)
"'"

So maybe you can use this, maybe you can't.

-- 
Remco Gerlich



More information about the Python-list mailing list