Python用\替换\\ [英] Python Replace \\ with \
问题描述
所以我似乎无法弄清楚这一点...我有一个字符串说,a\\
,我想要这样成为
b a\\\
。我已经尝试了以下所有操作,而且似乎没有工作;
b
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?
编辑我明白\是一个转义字符。我想在这里做的是将所有 \\\\
\\t
等 \\\
\t
等等,替换似乎没有像我想象的那样工作。
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'
我希望字符串a看起来像字符串b。但是替换不是像我以为这样替换斜线。
I want string a to look like string b. But replace isn't replacing slashes like I thought it would.
推荐答案
没有理由使用替换,Python来包括电池。您有一个编码字符串(使用 string_escape
encoding),您要解码它:
There is no reason to use replace for this, Python comes with batteries included.
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'
在Python 3中:
In Python 3:
>>> import codecs
>>> codecs.decode('\\n\\x21', 'unicode_escape')
'\n!'
这篇关于Python用\替换\\的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!