Python 将 \\ 替换为 \
我好像搞不清楚这个问题……我有一个字符串,比如说 "a\\nb"
,我想把它变成 "a\nb"
。我试过下面所有的方法,但都没有成功:
>>> 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'
我真的不明白为什么最后一个方法有效,因为这个方法运行得很好:
>>> a.replace("\\","%")
'a%nb'
我是不是漏掉了什么?
补充说明 我明白了,反斜杠(\)是一个转义字符。我想做的是把所有的 \\n
、\\t
等等都变成 \n
、\t
等等,但替换的效果似乎和我想象的不一样。
>>> a = "a\\nb"
>>> b = "a\nb"
>>> print a
a\nb
>>> print b
a
b
>>> a.replace("\\","\\")
'a\\nb'
>>> a.replace("\\\\","\\")
'a\\nb'
我想让字符串 a 看起来像字符串 b。但是替换的功能没有像我想的那样替换掉斜杠。
9 个回答
3
r'a\\nb'.replace('\\\\', '\\')
或者
'a\nb'.replace('\n', '\\n')
13
你可能不知道,反斜杠(\)是一个转义字符。
你可以看看这里:http://docs.python.org/reference/lexical_analysis.html,在2.4.1节“转义序列”中有详细说明。
最重要的是,\n表示换行符。而\\表示一个被转义的反斜杠 :D
>>> a = 'a\\\\nb'
>>> a
'a\\\\nb'
>>> print a
a\\nb
>>> a.replace('\\\\', '\\')
'a\\nb'
>>> print a.replace('\\\\', '\\')
a\nb
57
其实你不需要用替换来处理这个问题。
你现在有的是一个经过编码的字符串(使用了 string_escape
编码),你想要把它解码成正常的字符串:
>>> 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 中:
>>> import codecs
>>> codecs.decode('\\n\\x21', 'unicode_escape')
'\n!'