如何取消转义反斜杠转义字符串?

2024-05-20 12:28:19 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个字符串,它是另一个字符串的反斜杠转义版本。在Python中,有没有一种简单的方法来取消字符串的外观?例如,我可以:

>>> escaped_str = '"Hello,\\nworld!"'
>>> raw_str = eval(escaped_str)
>>> print raw_str
Hello,
world!
>>> 

但是,这涉及到将(可能不受信任的)字符串传递给eval(),这是一种安全风险。标准库中是否有接受字符串并生成不涉及安全性的字符串的函数?


Tags: 方法字符串版本helloworldraweval外观
3条回答

在python 3中,str对象没有decode方法,必须使用bytes对象。克里斯托弗的答案涵盖了python 2。

# create a `bytes` object from a `str`
my_str = "Hello,\\nworld"
# (pick an encoding suitable for your str, e.g. 'latin1')
my_bytes = my_str.encode("utf-8")

# or directly
my_bytes = b"Hello,\\nworld"

print(my_bytes.decode("unicode_escape"))
# "Hello,
# world"
>>> print '"Hello,\\nworld!"'.decode('string_escape')
"Hello,
world!"

您可以使用ast.literal_eval这是安全的:

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. (END)

像这样:

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

相关问题 更多 >