如何取消转义的反斜杠字符串? [英] How to un-escape a backslash-escaped string?

查看:494
本文介绍了如何取消转义的反斜杠字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串,它是另一个字符串的反斜杠转义版本。在Python中,有没有一种简便的方法可以使字符串不转义?例如,我可以这样做:

Suppose I have a string which is a backslash-escaped version of another string. Is there an easy way, in Python, to unescape the string? I could, for example, do:

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

但是,这涉及到将一个(可能不受信任的)字符串传递给eval(),这是安全隐患。标准库中是否有一个函数,该函数可以接收字符串并产生不涉及安全性的字符串?

However that involves passing a (possibly untrusted) string to eval() which is a security risk. Is there a function in the standard lib which takes a string and produces a string with no security implications?

推荐答案

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

这篇关于如何取消转义的反斜杠字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆