简体   繁体   English

如何使Python 2.x Unicode字符串不打印为u'string'?

[英]How to make Python 2.x Unicode strings not print as u'string'?

I'm currently testing a webservice that returns large amounts of JSON data in the form of dictionaries. 我目前正在测试一个以字典形式返回大量JSON数据的Web服务。 The keys and values for those dictionaries are all unicode strings, and thus they print like 这些字典的键和值都是unicode字符串,因此它们打印出来

{u'key1':u'value', u'key2':u'value2'}

when printed to the screen in the interactive interpreter. 在交互式解释器中打印到屏幕时。

Now imagine that this is a 3-level deep, 40-element dictionary. 现在想象一下,这是一个3级深度,40元素的字典。 All those u characters clutter up the display, making it hard to figure out, at a glance, what the real data actually is. 所有这些u字符都会使显示屏混乱,因此很难一目了然地看出实际数据究竟是什么。 Even when using pprint . 即使使用pprint

Is there any way to tell the interpreter that I don't care about the difference between normal strings and unicode strings? 有没有办法告诉解释器我不关心普通字符串和unicode字符串之间的区别? I don't need or want the u . 我不需要或想要

The only thing I've found that might have helped was the PYTHONIOENCODING environment variable. 我发现的唯一可能有帮助的是PYTHONIOENCODING环境变量。 Unfortunately, setting it to 'ascii' or 'latin-1' doesn't make those u 's go away. 不幸的是,将它设置为'ascii'或'latin-1'并不会让自己消失。

I'm using Python 2.6, and I use either the regular python interpreter, or iPython. 我正在使用Python 2.6,我使用常规python解释器或iPython。

if it's json you want, just print json : 如果它是你想要的json,只需打印json

>>> import json
>>> print json.dumps({u'key1':u'value', u'key2':u'value2'}, indent=4)
{
    "key2": "value2", 
    "key1": "value"
}

Why don't you create your own function to print the dictionary? 为什么不创建自己的函数来打印字典? Python's default format is OK for fast, easy debugging, but absolutely inapproapiate for a 3-level deep, 40-element dictionary. Python的默认格式可以快速,轻松地进行调试,但绝对适用于3级深度,40元素的字典。

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

相关问题 python 2.x中unicode字符串的string.ascii_letters相当于? - An equivalent to string.ascii_letters for unicode strings in python 2.x? 在强制字符串转换为unicode时,如何让python 2.x发出警告? - How can you make python 2.x warn when coercing strings to unicode? Python 2.x:如何自动执行unicode而不是字符串? - Python 2.x: how to automate enforcing unicode instead of string? Python 2.x字符串:Unicode与字节 - Python 2.x Strings: Unicode vs. Bytes 为什么Python 2.x会使用字符串格式+ Unicode引发异常? - Why does Python 2.x throw an exception with string formatting + unicode? 如何以原始语言打印unicode字符串的元组(不是u'foo'形式) - How to print tuples of unicode strings in original language (not u'foo' form) 如何在 Python 中解码以“%u”(百分号 + u)开头的 unicode 字符串 - How to decode the unicode string starting with “%u” (percent symbol + u) in Python 3 如何为Python 2.x ConfigParser指定unicode和其他转义文字 - How to specify a unicode and other escaped literals to Python 2.x ConfigParser Python 2.x 是否总是为打印语句返回一个字符串? - Does Python 2.x always return a string for print statements? python如何打印unicode字符串和列表? - How does python print unicode strings and lists?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM