How to replace a double backslash with a single backslash in python?

大城市里の小女人 提交于 2019-11-27 20:30:58

You can try codecs.escape_decode, this should decode the escape sequences.

I'm not getting the behaviour you describe:

>>> x = "\\\\\\\\"
>>> print x
\\\\
>>> y = x.replace('\\\\', '\\')
>>> print y
\\

When you see '\\\\' in your output, you're seeing twice as many slashes as there are in the string because each on is escaped. The code you wrote should work fine. Trying printing out the actual values, instead of only looking at how the REPL displays them.

To extend on Jeremy's answer, your problem is that '\' is an illegal string because \' escapes the quote mark, so your string never terminates.

It may be slightly overkill, but...

>>> import re
>>> a = '\\u201c\\u3012'
>>> re.sub(r'\\u[0-9a-fA-F]{4}', lambda x:eval('"' + x.group() + '"'), a)
'“〒'

So yeah, the simplest solution would ms4py's answer, calling codecs.escape_decode on the string and taking the result (or the first element of the result if escape_decode returns a tuple as it seems to in Python 3). In Python 3 you'd want to use codecs.unicode_escape_decode when working with strings (as opposed to bytes objects), though.

Python3:

>>> b'\\u201c'.decode('unicode_escape')
'“'

or

>>> '\\u201c'.encode().decode('unicode_escape')
'“'
fransua

Just print it:

>>> a = '\\u201c'
>>> print a
\u201c
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!