如何转换转义字符? [英] How to convert escaped characters?

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

问题描述

我想将包含转义字符的字符串转换为其正常形式,就像 Python 的词法解析器所做的那样:

<预><代码>>>>escaped_str = '一个\\\'例子\\\''>>>打印(转义字符串)一个\'例子\'>>>normal_str = normalize_str(escaped_str)>>>打印(normal_str)一个例子"

当然无聊的方法是将所有已知的转义字符一一替换:http://docs.python.org/reference/lexical_analysis.html#string-literals

你会如何在上面的代码中实现normalize_str()?

解决方案

>>> escaped_str = '一个 \\\'example\\''>>> 打印 escaped_str.encode('string_escape')一个\\\'例子\\\'>>> 打印 escaped_str.decode('string_escape')一个例子"

有几个类似的编解码器可用,例如 rot13 和 hex.

以上是 Python 2.x,但是——因为你说(在下面,在评论中)你使用的是 Python 3.x——虽然解码 Unicode 字符串对象是迂回的,但它是 仍然有可能.编解码器也已重命名为unicode_escape":

<前>Python 3.3a0(默认:b6aafb20e5f5,2011 年 7 月 29 日,05:34:11)[GCC 4.4.3] 在 linux2输入帮助"、版权"、信用"或许可"以获取更多信息.>>> escaped_str = "一个 \\\'example\\'">>> 导入编解码器>>> 打印(codecs.getdecoder("unicode_escape")(escaped_str)[0])一个例子"

I want to convert strings containing escaped characters to their normal form, the same way Python's lexical parser does:

>>> escaped_str = 'One \\\'example\\\''
>>> print(escaped_str)
One \'Example\'
>>> normal_str = normalize_str(escaped_str)
>>> print(normal_str)
One 'Example'

Of course the boring way will be to replace all known escaped characters one by one: http://docs.python.org/reference/lexical_analysis.html#string-literals

How would you implement normalize_str() in the above code?

解决方案

>>> escaped_str = 'One \\\'example\\\''
>>> print escaped_str.encode('string_escape')
One \\\'example\\\'
>>> print escaped_str.decode('string_escape')
One 'example'

Several similar codecs are available, such as rot13 and hex.

The above is Python 2.x, but – since you said (below, in a comment) that you're using Python 3.x – while it's circumlocutious to decode a Unicode string object, it's still possible. The codec has been renamed to "unicode_escape" too:

Python 3.3a0 (default:b6aafb20e5f5, Jul 29 2011, 05:34:11) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> escaped_str = "One \\\'example\\\'"
>>> import codecs
>>> print(codecs.getdecoder("unicode_escape")(escaped_str)[0])
One 'example'

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

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