Python列表或者字典里面的中文如何处理?
PHPz
PHPz 2017-04-18 10:26:13
0
3
567

已经是utf8编码了,但是在print mylist的时候打印出来的是它的utf8编码而不是我想要的汉字,网上有人说可以json.dumps的,但是这样的话就变成了string了不是列表或字典了。有什么办法可以在保证类型不改变的情况下可以通过mylist[0]这种下标访问方式访问到正确的中文,因为我想拿出来和另外的一个中文单词比较是否相等。谢谢。

PHPz
PHPz

学习是最好的投资!

reply all(3)
Ty80
>>> list
[u'\u4e2d\u6587', u'\u6211\u662f\u4e2d\u6587', u'\u6211\u8fd8\u662f\u4e2d\u6587']
>>> list[0]
u'\u4e2d\u6587'
>>> list[0].encode('utf8')
'\xe4\xb8\xad\xe6\x96\x87'
>>> str = list[0].encode('utf8')
>>> print str
中文
伊谢尔伦

If you just want the format to look good. . .

import json
zhlist = [u'中文', u'英文']
print json.dumps(zhlist, ensure_ascii=False, indent=2)

They look the same when printed out, but different when compared. Most likely, the unicode对象,一个是string对象,用type(obj)method is to check the specific types of the two values ​​you want to compare.
If you want to fully understand the coding issue, you can refer to the first two answers below this question.

洪涛

Loop output and that’s it.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!