【问题标题】:Byte string to list要列出的字节字符串
【发布时间】:2019-07-25 10:37:40
【问题描述】:

我从机器接收到串行数据字节字符串b'001 000000000000000000 000 4.98 135.1 100.8 0.00 0.00 6.6\r\n'。如何创建像[001, 000000000000000000, 000, 4.98, 135.1, 100.8, 0.00, 6.6] 这样的列表?

【问题讨论】:

  • 检查 split() 函数。

标签: python python-3.x list byte


【解决方案1】:

这是我的答案,使用 strip 删除 \r \n 并拆分(默认空格)以拆分到列表中

s = b'001 000000000000000000 000 4.98 135.1 100.8 0.00 0.00 6.6\r\n'
l = s.strip().split()

输出

['001', '000000000000000000', '000', '4.98', '135.1', '100.8', '0.00', '0.00', '6.6']

【讨论】:

  • 这会保留字节类,而不是字符串。它输出[b'001', b'000000000000000000', b'000', b'4.98', b'135.1', b'100.8', b'0.00', b'0.00', b'6.6']。 OP似乎也希望输出值为floats
  • @yatu 那不是真的,它们是字符串而不是列表中的字节。 >>> print(l) ['001', '000000000000000000', '000', '4.98', '135.1',​​ '100.8', '0.00', '0.00', '6.6'] >>> print(repr (l)) ['001', '000000000000000000', '000', '4.98', '135.1',​​ '100.8', '0.00', '0.00', '6.6']
【解决方案2】:

首先,将字节转换为字符串,然后使用 strip() 删除 \r\n 最后根据空间分割

a = b'001 000000000000000000 000 4.98 135.1 100.8 0.00 0.00 6.6\r\n' 
print(a.decode("utf-8").strip().split())

结果

['001', '000000000000000000', '000', '4.98', '135.1', '100.8', '0.00', '0.00', '6.6']

【讨论】:

    【解决方案3】:
        str =b'001  000000000000000000  000 4.98 135.1 100.8 0.00 0.00   6.6\r\n'
        Result =[i for i in str.strip().split()]
        #Result = ['001', '000000000000000000', '000', '4.98', '135.1', '100.8', '0.00', '0.00', '6.6']
    

    【讨论】:

      【解决方案4】:

      使用列表推导

      • decode()- 返回从给定字节解码的字符串。
      • split() - 在用指定的分隔符分隔给定字符串后返回字符串列表。
      • float() - 从数字或字符串中返回浮点数。

      例如

      str1 = b'001 000000000000000000 000 4.98 135.1 100.8 0.00 0.00 6.6\r\n'
      my_list = [float(i) for i in str1.decode("utf-8").split()]
      print(my_list)
      

      O/P:

      [1.0, 0.0, 0.0, 4.98, 135.1, 100.8, 0.0, 0.0, 6.6]
      

      【讨论】:

      • @yatu 感谢您提供的信息。我会更新答案。
      猜你喜欢
      • 2017-08-31
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      相关资源
      最近更新 更多