如何在 Python 中将 \ 替换为 \\?


有两种方法可以在 Python 中将 \ 替换为 \\ 或对逃逸反斜杠转义字符进行转义。第一个方法是使用 literal_eval 来评估字符串。请注意,使用该方法时,你需要用另一层引号将字符串括起来。例如:

>>> import ast
>>> a = '"Hello,\nworld"'
>>> print ast.literal_eval(a)
Hello,
world

另一种方法是使用字符串类的 decode('string_escape') 方法。例如:

>>> print "Hello,\nworld".decode('string_escape')
Hello,
world

更新于: 30-Sep-2019

679 浏览量

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.