Python将\替换为

所以我似乎无法弄清楚这一点...我有一个字符串说,
"a\nb"
我希望这成为
"anb"
。我已经尝试了以下所有,似乎没有工作;
>>> 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 = "anb"
>>> print a
anb
>>> print b
a
b
>>> a.replace("\","\")
'a\nb'
>>> a.replace("\\","\")
'a\nb'
我希望字符串a看起来像字符串b。但是替换不是像我想的那样替换斜线。     
已邀请:
没有必要使用替换。 你有一个编码的字符串(使用
string_escape
编码),你想解码它:
>>> s = r"EscapednNewline"
>>> print s
EscapednNewline
>>> s.decode('string_escape')
'EscapednNewline'
>>> print s.decode('string_escape')
Escaped
Newline
>>> "a\nb".decode('string_escape')
'anb'
在Python 3中:
>>> import codecs
>>> codecs.decode('\n\x21', 'unicode_escape')
'n!'
    
你错过了,那就是逃脱角色。 请看这里: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('\\', '\')
anb
    
你的原始字符串
a = 'a\nb'
实际上没有两个
''
字符,第一个是后者的逃脱。如果你这样做,
print a
,你会发现你实际上只有一个
''
角色。
>>> a = 'a\nb'
>>> print a
anb
但是,如果你的意思是将
'n'
解释为换行符,而不是逃避斜线,那么:
>>> b = a.replace('\n', 'n')
>>> b
'anb'
>>> print b
a
b
    
这是因为,即使在“原始”字符串(=在起始引号之前具有
r
的字符串),未转义的转义字符也不能是字符串中的最后一个字符。这应该工作:
'\ '[0]
    
在Python字符串文字中,反斜杠是一个转义字符。当交互式提示符显示字符串的值时,也是如此。它将为您提供字符串的文字代码表示。使用
print
语句查看字符串的实际外观。 这个例子显示了不同之处:
>>> '\'
'\'
>>> print '\'

    
r'a\nb'.replace('\\', '\')
要么
'anb'.replace('n', '\n')
    

要回复问题请先登录注册