re.escape(): Python’s equivalent of PHP’s addslashes()

Posted on 22 April, 2007

6



PHP has a very handy function addslashes which escapes, by prefixing backslashes, characters that can cause undesired effects in SQL queries (read SQL injection). Coding a login page in Python had me hard pressed to find something similar in Python to escape characters retrieved from login forms. I won’t say I searched across the seven seas, but as much as I looked, I discovered the “escape” function from the “re” module. I cannot find a reference online (I need to search better and more thoroughly), but re.escape in effect escapes all non-alphanumeric characters in string given to it as argument.

The __doc__ string for re.escape says:

escape(pattern)
    Escape all non-alphanumeric characters in pattern.

About these ads
Posted in: General