ali*_*igf 6 python string-formatting
我想将包含转义字符的字符串转换为它们的正常形式,就像Python的词法解析器一样:
>>> escaped_str = 'One \\\'example\\\''
>>> print(escaped_str)
One \'Example\'
>>> normal_str = normalize_str(escaped_str)
>>> print(normal_str)
One 'Example'
Run Code Online (Sandbox Code Playgroud)
当然,无聊的方法是逐个替换所有已知的转义字符:http: //docs.python.org/reference/lexical_analysis.html#string-literals
您将如何normalize_str()在上面的代码中实现?
Fre*_*urk 20
>>> escaped_str = 'One \\\'example\\\''
>>> print escaped_str.encode('string_escape')
One \\\'example\\\'
>>> print escaped_str.decode('string_escape')
One 'example'
几个类似的编解码器是可用的,如ROT13和十六进制.
以上是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'
SingleNegationElimination 已经提到过这一点,但这里有一个例子:
在Python 3中:
>>>escaped_str = 'One \\\'example\\\''
>>>print(escaped_str.encode('ascii', 'ignore').decode('unicode_escape'))
One 'example'
Run Code Online (Sandbox Code Playgroud)
我认为这个问题确实是:
我有一个字符串格式,好像它是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?
Run Code Online (Sandbox Code Playgroud)
为了比较,走另一条路:
>>> 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?"'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15450 次 |
| 最近记录: |