string escaping problems with MySQLdb

Tim Hochberg tim.hochberg at ieee.org
Tue Jan 9 10:18:27 EST 2001


The mysterious BxT spake thusly:

> Hi, i know this is a new-bie question,
> i'm using MySQLdb and, as i'm extracting records, i get string escaped as
> follows:
> for example, instead of ß i'm getting \\337 (yes, with doppel \). When i'm
> printing the string i'm getting blah\337 (internally is blah\\337).

The string you are getting only has a single '\', it is displayed with two
because a "\337" is the escape code for the beta symbol. Hmmm, that's not
very clear, I suggest you peruse the manual and or play around till this
becomes clear. However, the difference you are seeing the string displayed
in the interpreter and the string printed is that printing formats stuff
using the str function, while in the interpreter repr is used.

>I tried
> to use string.replace but it's giving me the same string. Is there a way
to
> print blahß?

I'm sure there's a better way, but:

import re
print re.sub(r"\\(\d\d\d)", lambda x : chr(int(x.group(1),8)), myString)

or more clearly:

escapedOctal = re.compile(r"\\(\d\d\d)")
def matchToChr(match):
    n = int(match.group(1), 8)
    return chr(n)

print re.sub(escapedOctal, matchToChr, myString)


I'll let you figure out how that actually works....

-tim







More information about the Python-list mailing list