如何转换转义字符?
我想把包含转义字符的字符串转换成它们的正常形式,就像Python的词法解析器那样:
>>> escaped_str = 'One \\\'example\\\''
>>> print(escaped_str)
One \'Example\'
>>> normal_str = normalize_str(escaped_str)
>>> print(normal_str)
One 'Example'
当然,最无聊的方法就是一个一个地替换所有已知的转义字符: http://docs.python.org/reference/lexical_analysis.html#string-literals
那么你会如何在上面的代码中实现 normalize_str()
呢?
4 个回答
6
我想这个问题其实是:
我有一个字符串,它看起来像是Python代码的一部分。我该怎么做才能安全地解析它,让字符串中的
\n
变成换行符,字符串两边的引号也能被正确处理呢?
可以试试ast.literal_eval
。
>>> import ast
>>> print ast.literal_eval(raw_input())
"hi, mom.\n This is a \"weird\" string, isn't it?"
hi, mom.
This is a "weird" string, isn't it?
为了对比,反过来做的话:
>>> print repr(raw_input())
"hi, mom.\n This is a \"weird\" string, isn't it?"
'"hi, mom.\\n This is a \\"weird\\" string, isn\'t it?"'
7
SingleNegationElimination已经提到过这个,但这里有一个例子:
在Python 3中:
>>>escaped_str = 'One \\\'example\\\''
>>>print(escaped_str.encode('ascii', 'ignore').decode('unicode_escape'))
One 'example'
27
>>> escaped_str = 'One \\\'example\\\'' >>> print escaped_str.encode('string_escape') One \\\'example\\\' >>> print escaped_str.decode('string_escape') One 'example'
有几种类似的编码方式可以使用,比如 rot13 和 hex。
上面提到的是 Python 2.x 的内容,但因为你在下面的评论中提到你在用 Python 3.x,所以虽然解码一个 Unicode 字符串对象有点绕,但还是可以做到的。这个编码方式也被重新命名为 "unicode_escape":
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'