Python Replace \\ with \
Solution 1:
There's no need to use replace for this.
What you have is a encoded string (using the string_escape
encoding) and you want to decode it:
>>> s = r"Escaped\nNewline"
>>> print s
Escaped\nNewline
>>> s.decode('string_escape')
'Escaped\nNewline'
>>> print s.decode('string_escape')
Escaped
Newline
>>> "a\\nb".decode('string_escape')
'a\nb'
In Python 3:
>>> import codecs
>>> codecs.decode('\\n\\x21', 'unicode_escape')
'\n!'
Solution 2:
You are missing, that \ is the escape character.
Look here: http://docs.python.org/reference/lexical_analysis.html at 2.4.1 "Escape Sequence"
Most importantly \n is a newline character. And \\ is an escaped escape character :D
>>> a = 'a\\\\nb'
>>> a
'a\\\\nb'
>>> print a
a\\nb
>>> a.replace('\\\\', '\\')
'a\\nb'
>>> print a.replace('\\\\', '\\')
a\nb
Solution 3:
Your original string, a = 'a\\nb'
does not actually have two '\'
characters, the first one is an escape for the latter. If you do, print a
, you'll see that you actually have only one '\'
character.
>>> a = 'a\\nb'
>>> print a
a\nb
If, however, what you mean is to interpret the '\n'
as a newline character, without escaping the slash, then:
>>> b = a.replace('\\n', '\n')
>>> b
'a\nb'
>>> print b
a
b