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

python2.7 中\x00 怎么删除

  •  
  •   QBugHunter · 2021-03-29 15:51:49 +08:00 · 2075 次点击
    这是一个创建于 1123 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2021-03-30 05:07:46 +08:00
    shuax
        1
    shuax  
       2021-03-29 16:03:29 +08:00
    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  
       2021-03-29 16:18:36 +08:00
    "157PU\x00\x00\x00\x00\x00".strip('\x00')
    Keyes
        3
    Keyes  
       2021-03-29 16:35:42 +08:00 via iPhone
    这种直接把一整个缓冲区丢出来的服务端真心蛋疼
    Olament
        4
    Olament  
       2021-03-29 16:58:13 +08:00
    a.rstrip('\x00')
    julyclyde
        5
    julyclyde  
       2021-03-29 17:08:47 +08:00
    用\n 那不是显然不好使么……
    fuis
        6
    fuis  
       2021-03-29 20:06:30 +08:00
    用楼主的话来回复楼主:

    没有十年脑。。。。
    算了
    dingwen07
        7
    dingwen07  
       2021-03-29 22:49:11 +08:00 via iPhone
    a.strip('\x00')不行就
    a.strip('\\x00')
    iptables
        8
    iptables  
       2021-03-30 05:06:23 +08:00
    >>> "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  
       2021-03-30 05:07:46 +08:00
    \n 相当于 \x0a,和 \x00 完全不一样啊
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3295 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 14:16 · PVG 22:16 · LAX 07:16 · JFK 10:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.