Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Replace \\ with \

So I can't seem to figure this out... I have a string say, "a\\nb" and I want this to become "a\nb". I've tried all the following and none seem to work;

>>> a 'a\\nb' >>> a.replace("\\","\")   File "<stdin>", line 1     a.replace("\\","\")                       ^ SyntaxError: EOL while scanning string literal >>> a.replace("\\",r"\")   File "<stdin>", line 1     a.replace("\\",r"\")                        ^ SyntaxError: EOL while scanning string literal >>> a.replace("\\",r"\\") 'a\\\\nb' >>> a.replace("\\","\\") 'a\\nb' 

I really don't understand why the last one works, because this works fine:

>>> a.replace("\\","%") 'a%nb' 

Is there something I'm missing here?

EDIT I understand that \ is an escape character. What I'm trying to do here is turn all \\n \\t etc. into \n \t etc. and replace doesn't seem to be working the way I imagined it would.

>>> a = "a\\nb" >>> b = "a\nb" >>> print a a\nb >>> print b a b >>> a.replace("\\","\\") 'a\\nb' >>> a.replace("\\\\","\\") 'a\\nb' 

I want string a to look like string b. But replace isn't replacing slashes like I thought it would.

like image 994
kand Avatar asked Mar 03 '11 21:03

kand


People also ask

How can I replace with in Python?

Python String replace() MethodThe replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.

How do you replace part of a string in Python?

Python String | replace() replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.

How do you replace words with inputs in Python?

To replace a string in Python, use the string. replace() method. Sometimes you will need to replace a substring with a new string, and Python has a replace() method to achieve it.

How do you change the backslash with a forward slash in Python?

replace('\\', '/') works just fine.


1 Answers

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!' 
like image 159
Jochen Ritzel Avatar answered Sep 22 '22 13:09

Jochen Ritzel