繁体   English   中英

如何防止str将unicode字符编码为十六进制代码?

[英]How to prevent str to encode unicode characters as hex codes?

当我直接在Python中print unicode字符串时,我看到的字符串与我的字符串具有相同的字符。 当我将其嵌入某个容器(放入列表,地图等)时, str表示将Unicode字符转换为\\ uXXXX表示。 有趣的是,我可以使用字符串在此容器上调用print ,但是不能print str字符串本身的print str (给出UnicodeEncodeError)。

我可以配置str来将嵌套的字符串编码为UTF8字符串吗? 查看此十六进制符号会使调试非常痛苦。

例:

>>> v = u"abc123абв"
>>> d = [v]
>>> print v
abc123абв
>>> print d
[u'abc123\u0430\u0431\u0432']
>>> print str(v)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec cant encode characters in position 6-8: ordinal not in range(128)
>>> print str(d)
[u'abc123\u0430\u0431\u0432']

我在ubuntu上使用Python 2.7.6,控制台编码为UTF8。 Python似乎也使用UTF8:

>>> print(sys.stdout.encoding)
UTF-8
>>> print(locale.getpreferredencoding())
UTF-8
>>> print(sys.getfilesystemencoding())
UTF-8

print [v]调用repr(v) ,它按原样返回可打印ascii的字符,而其他所有内容都使用\\x\\u\u003c/code> , \\U ,...进行转义。

请记住,诸如dict(a=1)类的对象与其文本表示形式不同( repr(dict(a=1)) )。 Unicode字符串也是一个对象( type(v) == unicode )像其他对象一样,因此repr(v) is not v (顺便说一句, repr(repr(v)) is not repr(v) -考虑一下) 。

要在Python控制台中显示人类可读的文本以进行调试,可以提供自定义sys.displayhook例如,您可以使用sys.stdout.encoding对任何(嵌入式) unicode对象进行编码。 在Python 3中, repr(unicode_string)返回可在当前环境中按原样打印的Unicode字符(将导致UnicodeEncodeError字符被转义)。

str(v)引发UnicodeEncodeError是无关的。 str(v)调用v.encode(sys.getdefaultencoding()) ,因此,对于任何带有非ascii字符的unicode字符串,它都会失败。 不要在Unicode字符串上调用str() (这几乎总是一个错误),而是直接打印Unicode。

不要改变str ,改变way of thinking

如果您需要打印netsted元素而不是从容器中获取并打印它-不要打印所有容器。

v = u"abc123абв"
d = [v, v, v]

print d[0]
# abc123абв

print ", ".join(d)
# abc123абв, abc123абв, abc123абв

顺便说一句:出于测试/调试原因,Python打印十六进制代码(和其他元素)。

当你看到

[u'abc123\u0430\u0431\u0432']

您知道:这是带有unicode文本( u' )的列表( [] ),并且该文本中包含非ASCII字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM