The solution to this problem is to use the raw string as replacement text. The following actions will not be performed:
re.sub('this', 'This \\', 'this is a text')
It will throw an error: dummy output (end of line)
But the following will work just fine:
re.sub('this', r'This \\', 'this is a text')
Now the question is how to convert the string generated at run time to the original string in Python. You can find a solution for this here . But I prefer to use a simpler method for this:
def raw_string(s): if isinstance(s, str): s = s.encode('string-escape') elif isinstance(s, unicode): s = s.encode('unicode-escape') return s
The above method can only convert ascii and unicode strings to raw strings. Well, this has worked great for me so far :)
rtnpro Jan 01 '11 at 9:59 2012-01-01 09:59
source share