所以我似乎想不出.我有一个字符串说,"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,但是替换不是像我想的那样替换斜杠。
发布于 2011-03-03 21:56:54
没有必要对此使用替换。
您所拥有的是一个编码字符串(使用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!'发布于 2011-03-03 21:38:10
你失踪了,那就是转义字符。
看这里: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发布于 2011-03-03 21:44:00
r'a\\nb'.replace('\\\\', '\\')或
'a\nb'.replace('\n', '\\n')https://stackoverflow.com/questions/5186839
复制相似问题