Problems replacing \ with \\
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon Apr 21 22:30:20 EDT 2008
(top posting corrected)
En Mon, 21 Apr 2008 21:12:44 -0300, ockman at gmail.com <ockman at gmail.com>
escribió:
>> > def escape(string):
>> > """
>> > Escape both single quotes and blackslashes
>> > >>> x = r"fun\fun"
>> > >>> escape(x)
>> > 'fun\\\\fun'
>> > """
>> > string = string.replace('\\', '\\\\')
>> > return string
>>
>> > Failed example:
>> > escape(x)
>> > Expected:
>> > 'fun\\fun'
>> > Got:
>> > 'fun\x0cun'
>>
>> Your doctest is in a triple-quoted string which contains the line:
>>
>> >>> x = r"fun\fun"
>> which is the same as:
>>
>> >>> x = r"fun\x0cun"
>>
>> If you wrap a raw string in just quotes that is isn't a raw string any
>> longer!
> Thank you for the response. I'm not sure I understand the last
> sentence, although I think I get the idea. How do I create a proper
> doctest?
r"This is a raw string"
"""
r"This is NOT a raw string"
"""
r"""
r"This is a raw string too"
"""
What matters are the OUTER quotes.
Now, why do you want to escape the text yourself? Assuming you have a
DBAPI compatible module, use bound parameters when you execute the query:
cursor.execute("insert ... values (?,?,?)", (name, address, year))
Those ? are placeholders for the actual values; no explicit quoting on the
values is required (the module itself, or the database, takes care of it).
Not all databases support the ? style, there are other ways. See
http://www.python.org/dev/peps/pep-0249/ for the DB API specification.
--
Gabriel Genellina
More information about the Python-list
mailing list