gpt4 book ai didi

python - Python 中的另一个 JSON/编码错误

转载 作者:太空宇宙 更新时间:2023-11-03 15:58:26 24 4
gpt4 key购买 nike

我已阅读 Unicode HOWTO好几次了,解决了好多次类似的问题,还是不明白怎么办。任何人都可以帮助我如何正确打印此加载的 json ?

#!/usr/bin/env python2
# coding: utf8

import json

s = u'["poêle", "mangé"]'
print s
l = json.loads(s)
print l

我已经尝试了我能想到的所有编码/编码/解码/unicode组合...但第二个打印很丑陋:

$ python test.py
["poêle", "mangé"]
[u'po\xeale', u'mang\xe9']

感谢您的帮助

最佳答案

To pretty print your list try the following taken from this so question

打印repr(l).decode('unicode-escape')

Also, when you print a list, it prints the repr of the elements.

print l[0], l[1]print l 不同,因此您始终可以迭代元素并打印它们。 print l[0], l[1] 也将正确打印字符。

这应该可以帮助您理解差异

class MyClass(object):
def __repr__(self):
return "<repr: MyClass>"

def __str__(self):
return "<str: MyClass>"

l = [ MyClass(), MyClass(), MyClass() ]
print l
print l[0], l[1], l[2]

output

[<repr: MyClass>, <repr: MyClass>, <repr: MyClass>]
<str: MyClass> <str: MyClass> <str: MyClass>

关于python - Python 中的另一个 JSON/编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40563884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com