Within a Python string, certain sequences have special meaning. Each of these sequences begins with a backslash \
, known as the escape character. The values (and different escape methods) allowed in string literals are described in the Python documentation at http://www.python.org/doc/current/ref/strings.html. This is a brief summary.
Python recognizes the following escape sequences:
\\ Backslash (\) \' Single quote (') \" Double quote (") \a ASCII Bell (BEL) \b ASCII Backspace (BS) \f ASCII Formfeed (FF) \n ASCII Linefeed (LF) \N{name} Character named name in the Unicode database (Unicode only) \r ASCII Carriage Return (CR) \t ASCII Horizontal Tab (TAB) \uxxxx Character with 16-bit hex value xxxx (Unicode only) \Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only) \v ASCII Vertical Tab (VT) \ooo Character with octal value ooo \xhh Character with hex value hh
\b
is interpreted as a backspace, but \B
is not.
You can use these characters in SQL exactly the same way as you would in Python. For example 'end of one line\nstart of new line'
is a valid SQL string containing a line break in the middle and could be used like this:
cursor.execute("INSERT INTO table (columnOne) VALUES ('end of one line\nstart of new line')")
There is one important point to note about how Python (and hence web.database ) deals with these escape characters. If a string contains a backslash \
but the character after the backslash is not a character which can be escaped then the single backslash is treated as a single backslash. If the character can be used in an escape sequence then the backslash is treated as an escape character and the character is escaped.
Note: All examples in this section are from the Python prompt not the web.database one.
For example:
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print 'hello\%world' hello\%world >>> print 'hello\nworld' hello world >>>
If a string contains both escaped and non-escaped characters Python guesses which are backslashes and which are escape characters:
>>> print 'hello\nworld\%again' hello world\%again >>>
If a string contains a double backslash \\
it is always treated as an escaped backslash character and printed as \
.
>>> print '\\%' \% >>> print '\%' \%
This means that the following expression is True:
>>> print '\\%' == '\%' True >>>
But the following is not:
>>> print '\\\\%' == '\\%' False >>>
When writing Python strings you have to be very careful how the backslash character is being used and then you will have no problems.