Maison  >  Questions et réponses  >  le corps du texte

python 编码问题,求助各位大神

想请问下拿到一串unicode编码串,要怎么才能转换中文输出

我发现直接

print u'\u4ed7\u5251\u5929\u6daf'

或者

a = u"\u4ed7\u5251\u5929\u6daf"
print a

是可以输出中文

但是如果把串赋值到变量,用decode,encode转换都不行

a = '\u4ed7\u5251\u5929\u6daf'

不知道怎样print a才能输出中文了?

黄舟黄舟2713 Il y a quelques jours449

répondre à tous(4)je répondrai

  • 黄舟

    黄舟2017-04-17 17:54:27

    在Python3中,字符串类型全改成unicode的了,你如下用没问题,输出是一样的

    # -*- coding: utf-8 -*-
    
    a = u"\u4ed7\u5251\u5929\u6daf"
    print(a, len(a), type(a))
    
    b = "\u4ed7\u5251\u5929\u6daf"
    print(b, len(b), type(b))
    
    

    而在Python2.7中,加u表示unicode,不加表示字符串,所以你直接去掉u并得到的并不是等价的字符串,你可以分别打印数据类型、字符串长度就能看出来

    répondre
    0
  • 高洛峰

    高洛峰2017-04-17 17:54:27

    最后一句话
    a = 'u4ed7u5251u5929u6daf'
    a 实际上已经是字符串了
    因此要把a转换成unicode才能print打印中文,
    可以使用
    print a.decode('unicode-escape')
    参考
    http://stackoverflow.com/questions/10268518/python-string-to-unicode

    répondre
    0
  • 黄舟

    黄舟2017-04-17 17:54:27

    最后一句 a = 'u4ed7u5251u5929u6daf' 为什么要把引号前的u丢掉呢?

    répondre
    0
  • 天蓬老师

    天蓬老师2017-04-17 17:54:27

    Python字符串前面那个u表示这个字符串要以unicode编码来解析。
    你使用decode,意思是你要将'u4ed7u5251u5929u6daf'这个字符串,转成unicode编码。

    répondre
    0
  • Annulerrépondre