【问题标题】:Python3 Convert bytes object to intPython3将字节对象转换为int
【发布时间】:2019-03-06 16:18:59
【问题描述】:

我有一个从套接字接收的字节对象,我想提取它包含的整数值。

看起来像这样

input = b'1         \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

我试过了

tmp_str = input.decode('ascii').strip()
int(tmp_str)

错误:

ValueError: invalid literal for int() with base 10: '1         \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

但是tmp_str的类型是'str',但是长度是20..看起来对象没有改变,只是它的一些表示改变了..

>>> print(tmp_str)
1
>>> len (tmp_str)
20
>>> type(tmp_str)
<class 'str'>
>>> type(input)
<class 'bytes'>

如何从中提取 int?

【问题讨论】:

    标签: python python-3.x string int


    【解决方案1】:

    str.strip()bytes.strip() 不会删除 NUL 字节,除非您明确告诉它们,因为 NUL 字节不是空格。

    您不必将字节解码为 str,但是,int() 可以直接接受 bytes 对象。只需调用 bytes.strip() 并告诉它删除空格和 NUL:

    int(input.strip(b' \x00')
    

    演示:

    >>> input = b'1         \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    >>> int(input.strip(b' \x00'))
    1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 2019-09-02
      • 2016-03-04
      • 2016-02-20
      相关资源
      最近更新 更多