search

Home  >  Q&A  >  body text

Python列表或者字典里面的中文如何处理?

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

PHPzPHPz2875 days ago610

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:28:13

    >>> 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
    中文
    

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:28:13

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:28:13

    Loop output and that’s it.

    reply
    0
  • Cancelreply