V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
QBugHunter
V2EX  ›  Python

python2.7 中\x00 怎么删除

  •  
  •   QBugHunter · Mar 29, 2021 · 3027 views
    This topic created in 1857 days ago, the information mentioned may be changed or developed.

    Python2.7

    首先是服务器穿过来的字节流,需要转换为 string(按照 ascii),比如 16 进制字节流是

    "31 35 37 50 55 00 00 00 00 00"

    需要转为 string

    "157PU"

    于是有下列代码

    def byte_to_string(d):
        return binascii.a2b_hex(d)
    

    但实际转换结果为

    a = byte_to_string('31 35 37 50 55 00 00 00 00 00')
    print a
    >>>"157PU\x00\x00\x00\x00\x00"
    

    请问这个 string 里几个\x00 怎么删除,我用

    a.strip()
    a.replace("\n","")
    

    都不好使,最用用 len(a)测试的时候结果都还是 10

    9 replies    2021-03-30 05:07:46 +08:00
    momo1999
        1
    momo1999  
       Mar 29, 2021
    s = "31 35 37 50 55 00 00 00 00 00"
    b = bytes.fromhex(s)
    s = b.decode()
    s = s.replace('\0', '')
    ruanimal
        2
    ruanimal  
       Mar 29, 2021
    "157PU\x00\x00\x00\x00\x00".strip('\x00')
    Keyes
        3
    Keyes  
       Mar 29, 2021 via iPhone
    这种直接把一整个缓冲区丢出来的服务端真心蛋疼
    Olament
        4
    Olament  
       Mar 29, 2021
    a.rstrip('\x00')
    julyclyde
        5
    julyclyde  
       Mar 29, 2021
    用\n 那不是显然不好使么……
    fuis
        6
    fuis  
       Mar 29, 2021
    用楼主的话来回复楼主:

    没有十年脑。。。。
    算了
    dingwen07
        7
    dingwen07  
       Mar 29, 2021 via iPhone
    a.strip('\x00')不行就
    a.strip('\\x00')
    iptables
        8
    iptables  
       Mar 30, 2021
    >>> "157PU\x00\x00\x00\x00\x00"
    '157PU\x00\x00\x00\x00\x00'
    >>> a = "157PU\x00\x00\x00\x00\x00"
    >>> a.rstrip('\x00')
    '157PU'
    >>> a.rstrip('\n')
    '157PU\x00\x00\x00\x00\x00'
    >>> a.rstrip('\0')
    '157PU'
    iptables
        9
    iptables  
       Mar 30, 2021
    \n 相当于 \x0a,和 \x00 完全不一样啊
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   903 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 21:04 · PVG 05:04 · LAX 14:04 · JFK 17:04
    ♥ Do have faith in what you're doing.