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。但是替换不是像我想的那样替换斜线。
没有找到相关结果
已邀请:
6 个回复
荤碗
编码),你想解码它:
在Python 3中:
皇小福另届
涸坍饺
实际上没有两个
字符,第一个是后者的逃脱。如果你这样做,
,你会发现你实际上只有一个
角色。
但是,如果你的意思是将
解释为换行符,而不是逃避斜线,那么:
丧泉缝锋
的字符串),未转义的转义字符也不能是字符串中的最后一个字符。这应该工作:
感秆暴壳
语句查看字符串的实际外观。 这个例子显示了不同之处:
蹄寄噬非芹
要么