推荐学习书目
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
ammzen
V2EX  ›  Python

Python 2.7 中字节字符串的处理求助

  •  
  •   ammzen · Jan 27, 2015 · 5666 views
    This topic created in 4132 days ago, the information mentioned may be changed or developed.

    现在收到4个字节字符串 s,Python读取得到的是\xff\x08\x00\x0a
    我想print显示为16进制, FF 08 00 0A

    print '%X %X %X %X' %(s)
    错误信息:TypeError: %X format: a number is required, not str

    修改一下
    print '%X %X %X %X' %(int(s))
    错误信息:ValueError: invalid literal for int() with base 10: '\xff\x08'

    后来又试了atoi
    print '%X%X%X%X' %(string.atoi(s, 16))
    错误信息:ValueError: invalid literal for int() with base 16: '\xff\x08\x00\n'

    后来发现最大的问题在于 \x 转义,如果是0x的话倒是可以解决,想问一下有什么办法可以解决这个问题吗

    5 replies    2015-01-27 11:24:09 +08:00
    jatsz
        1
    jatsz  
       Jan 27, 2015
    s.encode('hex') #如果是想转成hex的字符串的话
    print '%02X %02X %02X %02X' % (tuple(bytearray(s))) #带分隔的二进制字符串
    wartime
        2
    wartime  
       Jan 27, 2015
    print ' '.join('{:02X}'.format(ord(i)) for i in s)
    ammzen
        3
    ammzen  
    OP
       Jan 27, 2015
    @wartime 我刚刚在stack上也找到这个^_^
    ammzen
        4
    ammzen  
    OP
       Jan 27, 2015
    @jatsz 多谢!验证功能正常
    Sylv
        5
    Sylv  
       Jan 27, 2015
    import binascii

    s = '\xff\x08\x00\x0a'
    s = [binascii.hexlify(c).upper() for c in s]
    print ' '.join(s)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1394 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 17:12 · PVG 01:12 · LAX 10:12 · JFK 13:12
    ♥ Do have faith in what you're doing.