V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
redhatping
V2EX  ›  Python

一个小小的中文编码问题

  •  
  •   redhatping · 2015-06-13 09:45:27 +08:00 · 2452 次点击
    这是一个创建于 3247 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如,

    #coding:utf-8
    a = ['中国','美国']
    print a
    print a[1]

    结果是
    ['\xe4\xb8\xad\xe5\x9b\xbd', '\xe7\xbe\x8e\xe5\x9b\xbd']
    美国


    如何print a , 显示 ['中国','美国']


    为什么a[1],可以是中文,a 就是编码了呢?

    7 条回复    2015-06-13 10:58:48 +08:00
    yahoo21cn
        1
    yahoo21cn  
       2015-06-13 10:08:36 +08:00
    print str(a).decode('string_escape')
    blueset
        2
    blueset  
       2015-06-13 10:21:30 +08:00
    用 Python3 测试了一下

    >>> a = ['中国','美国']
    >>> print (a)
    ['中国', '美国']
    redhatping
        3
    redhatping  
    OP
       2015-06-13 10:22:15 +08:00
    @blueset python2呢
    redhatping
        4
    redhatping  
    OP
       2015-06-13 10:23:04 +08:00
    @yahoo21cn 再请问一下,为什么是这样呢,a[1],是中文呢?
    yahoo21cn
        5
    yahoo21cn  
       2015-06-13 10:39:59 +08:00   ❤️ 1
    因为默认在list打印的是utf-8编码,你如果不想打印编码,而是显示字型,需要string_escape解码一下
    yetone
        6
    yetone  
       2015-06-13 10:43:45 +08:00 via iPhone
    试一下 from __future__ import unicode_literals
    redhatping
        7
    redhatping  
    OP
       2015-06-13 10:58:48 +08:00
    @yahoo21cn 谢谢 :)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1002 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:58 · PVG 07:58 · LAX 16:58 · JFK 19:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.