((Python)转义所有'\'esape字符

问题描述 投票:0回答:2

我有几个带有\的字符串。我尝试通过使用类似的替换功能不使用转义字符:

string.replace("\\", "\\\\")

它不起作用。当我直接将string.replace("\n", "\\n")用于\n时,它可以工作。有没有简单可行的解决方案?

python replace escaping
2个回答
0
投票

重要的是,replace并不作用于变量,而是返回应用了替换的副本:

this = "string\\string"
this.replace("\\", "")

print(this)
>"string\\string"

如果您想替换原始字符串,

this = this.replace("\\", "")

-2
投票

使用raw strings

r"This \ string \ includes '\'s"
© www.soinside.com 2019 - 2024. All rights reserved.