En Wed, 16 Dec 2009 11:09:32 -0300, Ed Keith <e_...@yahoo.com> escribió:

I am having a problem when substituting a raw string. When I do the following:

re.sub('abc', r'a\nb\nc', '123abcdefg')

I get

"""
123a
b
cdefg
"""

what I want is

r'123a\nb\ncdefg'

From http://docs.python.org/library/re.html#re.sub

        re.sub(pattern, repl, string[, count])

        ...repl can be a string or a function; if
        it is a string, any backslash escapes in
        it are processed. That is, \n is converted
        to a single newline character, \r is
        converted to a linefeed, and so forth.

So you'll have to double your backslashes:

py> re.sub('abc', r'a\\nb\\nc', '123abcdefg')
'123a\\nb\\ncdefg'

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to