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
gogobody
V2EX  ›  Python

请教 Python3 bytearray 的问题

  •  
  •   gogobody · 2017-09-12 09:10:45 +08:00 · 2504 次点击
    这是一个创建于 2410 天前的主题,其中的信息可能已经有所发展或是发生改变。
    以前在 python2 中 a=bytes(bytearray((182,)))结果是 a='\xb6'
    现在在 Python3 运行结果是 a=b'\xb6',尝试各种 a.decode()均失败了,请问如何能在 Python3 得到和 Python2 一样的结果呢?
    5 条回复    2017-09-12 13:07:25 +08:00
    dikT
        1
    dikT  
       2017-09-12 09:13:39 +08:00
    str(a)
    ThunderEX
        2
    ThunderEX  
       2017-09-12 09:33:53 +08:00   ❤️ 1
    1. Python3 里面的 str 已经是 unicode str 了。
    2. bytes(bytearray((182,)))你用的就是 bytes 函数,所以理所当然的,无论 py2 还是 py3 都返回 bytes 类型,只不过 py2 时 bytes==str 而已。
    3. 如果你想得到的是 latin_1 编码的\xb6 代表的 str,请用.decode('latin-1')
    gogobody
        3
    gogobody  
    OP
       2017-09-12 09:35:03 +08:00 via Android
    @dikT str(a)得到的是''b'\xb6' ''😹
    gogobody
        4
    gogobody  
    OP
       2017-09-12 12:44:17 +08:00 via Android
    @ThunderEX 再请教一下,在 Python2 和 Python3 中用 chr()函数出的结果不一样,有什么替代方案吗
    ThunderEX
        5
    ThunderEX  
       2017-09-12 13:07:25 +08:00
    如果你要的是 unicode str,那就是 chr(250),如果你要的是 latin-1 格式编码,那就是 chr(250).encode('latin-1')
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1051 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:42 · PVG 06:42 · LAX 15:42 · JFK 18:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.