如何转换转义字符?

2024-05-15 02:42:01 发布

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

我想将包含转义字符的字符串转换为它们的普通形式,就像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()


Tags: 方法字符串http分析器exampleone形式print
3条回答

SingleNegationElimination已经提到了这一点,但这里有一个例子:

在Python 3中:

>>>escaped_str = 'One \\\'example\\\''
>>>print(escaped_str.encode('ascii', 'ignore').decode('unicode_escape'))
One 'example'
>>> escaped_str = 'One \\\'example\\\''
>>> print escaped_str.encode('string_escape')
One \\\'example\\\'
>>> print escaped_str.decode('string_escape')
One 'example'

几个类似的编解码器是available,比如rot13和hex。

上面是Python2.x,但是——由于您说过(在下面的注释中)您使用的是Python3.x——虽然解码Unicode字符串对象比较麻烦,但却是still possible。编解码器也已重命名为“unicode\u 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'

我想问题是:

I have a string that is formatted as if it were a part of Python source code. How can I safely interpret it so that \n within the string is transformed into a newline, quotation marks are expected on either end, etc. ?

尝试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?"'

相关问题 更多 >

    热门问题