【发布时间】:2013-08-31 13:49:11
【问题描述】:
(Python 3.3.2) 我必须取消对 re.escape() 调用返回的一些非 ASCII 转义字符的转义。我看到 here 和 here 方法不起作用。我在 100% UTF-8 环境中工作。
# pure ASCII string : ok
mystring = "a\n" # expected unescaped string : "a\n"
cod = codecs.getencoder('unicode_escape')
print( cod(mystring) )
# non ASCII string : method #1
mystring = "€\n"
# equivalent to : mystring = codecs.unicode_escape_decode(mystring)
cod = codecs.getdecoder('unicode_escape')
print(cod(mystring))
# RESULT = ('â\x82¬\n', 5) INSTEAD OF ("€\n", 2)
# non ASCII string : method #2
mystring = "€\n"
mystring = bytes(mystring, 'utf-8').decode('unicode_escape')
print(mystring)
# RESULT = â\202¬ INSTEAD OF "€\n"
这是一个错误吗?我是不是误会了什么?
任何帮助将不胜感激!
PS : 感谢 Michael Foukarakis 的评论,我编辑了我的帖子。
【问题讨论】:
-
你是在哪里执行终端/cmd中的文件还是?
-
"€\\n"不是 Unicode 转义字符串,因此您无法将其解码为任何有意义的内容。"€\n",如果是 Unicode 转义,将变为b'\\u20ac\\n'。所以,是的,你似乎误解了编码。 -
一个好点:我编辑了我的帖子。但我的问题与(非 unicode)€ 字符相同。
-
badcOre > 输出存储在文件中并在终端 (urxvt) 中打印。
标签: python unicode python-3.x