python raw string assignment

Tzury Bar Yochay picture Tzury Bar Yochay · Nov 24, 2011 · Viewed 18k times · Source

Given a file contains lines such as:

(?i:\bsys\.user_catalog\b)

While reading those line, I want the value to be a raw string (unescaped), meaning, in memory, line should be

r'(?i:\bsys\.user_catalog\b)'

instead of

(?i:\bsys\.user_catalog\b)

Which is escaped when passed over to libs such as sqlobject.

For instance, with sqlobject, if I state

Table(column=r'(?i:\bsys\.user_catalog\b)')

I get the desired results while if I state

Table(column='(?i:\bsys\.user_catalog\b)')

I do not.

So question is basically, I can I pass a raw string when I am not in declarative/assignment mode (e.g. a = r'string'), rather, the string is already in memory.

Answer

Tim Pietzcker picture Tim Pietzcker · Nov 24, 2011

The raw string notation is only used in Python source code; all strings declared as raw strings are "converted" to normal strings with the necessary escape sequences added during "compile time" (unlike (in Python 2) the two different string types string/Unicode string):

>>> r"\b"
'\\b'
>>> "Hello"
'Hello' 
>>> u"Hello"
u'Hello'

If you read the string from a file, it will already be correctly escaped.

(Assuming test.txt contains (?i:\bsys\.user_catalog\b)):

f = open("test.txt").read()
print f
print repr(f)

Output:

(?i:\bsys\.user_catalog\b)
'(?i:\\bsys\\.user_catalog\\b)'