Python Replace \\ with \ Python Replace \\ with \ python python

Python Replace \\ with \


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 sEscaped\nNewline>>> s.decode('string_escape')'Escaped\nNewline'>>> print s.decode('string_escape')EscapedNewline>>> "a\\nb".decode('string_escape')'a\nb'

In Python 3:

>>> import codecs>>> codecs.decode('\\n\\x21', 'unicode_escape')'\n!'


You are missing, that \ is the escape character.

Look here: http://docs.python.org/reference/lexical_analysis.htmlat 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 aa\\nb>>> a.replace('\\\\', '\\')'a\\nb'>>> print a.replace('\\\\', '\\')a\nb


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 aa\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 bab