php function "addslashes" / "removeslashes" in python
Fredrik Lundh
fredrik at pythonware.com
Tue Jul 9 20:04:11 EDT 2002
Lowel Stern wrote:
> Does anyone know if this exists already?
if you're doing database, you really should learn to use bound
parameters...
but if you insist, this might be a pretty good approximation:
import re
def addslashes(string, sub=re.compile(r"[\\\"']").sub):
def fixup(m):
return "\\" + m.group(0)
return sub(fixup, string)
def removeslashes(string, sub=re.compile(r"(?s)\\(.)|\\").sub):
def fixup(m):
ch = m.group(1)
if ch is None:
raise 'Parse Error: backslash at end of string'
if ch not in r"\\\"'":
raise 'Parse Error: unsupported character after backslash'
return ch
return sub(fixup, string)
</F>
More information about the Python-list
mailing list