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.
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.
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.
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.
replace('\\', '/') works just fine.
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!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With