推荐学习书目
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 · Sep 12, 2017 · 3392 views
    This topic created in 3213 days ago, the information mentioned may be changed or developed.
    以前在 python2 中 a=bytes(bytearray((182,)))结果是 a='\xb6'
    现在在 Python3 运行结果是 a=b'\xb6',尝试各种 a.decode()均失败了,请问如何能在 Python3 得到和 Python2 一样的结果呢?
    5 replies    2017-09-12 13:07:25 +08:00
    dikT
        1
    dikT  
       Sep 12, 2017
    str(a)
    ThunderEX
        2
    ThunderEX  
       Sep 12, 2017   ❤️ 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
       Sep 12, 2017 via Android
    @dikT str(a)得到的是''b'\xb6' ''😹
    gogobody
        4
    gogobody  
    OP
       Sep 12, 2017 via Android
    @ThunderEX 再请教一下,在 Python2 和 Python3 中用 chr()函数出的结果不一样,有什么替代方案吗
    ThunderEX
        5
    ThunderEX  
       Sep 12, 2017
    如果你要的是 unicode str,那就是 chr(250),如果你要的是 latin-1 格式编码,那就是 chr(250).encode('latin-1')
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4057 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 10:14 · PVG 18:14 · LAX 03:14 · JFK 06:14
    ♥ Do have faith in what you're doing.