You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python解码字节串存入列表仍带空字符,如何获取纯净字符串列表?

解决Python字节串解码后空字符残留问题

为啥会这样?

直接打印解码后的字符串时,终端会自动忽略\x00这种不可见的空字符,但这些字符其实一直存在于字符串里。当把字符串放进列表后,Python打印列表时会输出字符串的原始转义表示,所以原本隐藏的空字符就显式显示为\x00了。

怎么解决?

要得到干净的901LHD,只要把字符串里的所有\x00空字符去掉就行,下面是几种简单的方法:

方法1:用replace()直接替换所有空字符

这是最直接的方式,把所有\x00替换成空字符串:

byte_data = b'901\x00LHD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
decoded_str = byte_data.decode().replace('\x00', '')
print([decoded_str])  # 输出: ['901LHD']

方法2:按空字符分割后拼接有效内容

把字符串按\x00分割,再把所有非空的部分拼起来:

byte_data = b'901\x00LHD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
decoded_str = ''.join(byte_data.decode().split('\x00'))
print([decoded_str])  # 输出: ['901LHD']

方法3:先截断字节串再解码

如果字节串后面全是\x00,可以先把末尾的空字节去掉,再解码并清理中间的空字符:

byte_data = b'901\x00LHD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
# 先去掉字节串末尾的所有空字节
trimmed_byte_data = byte_data.rstrip(b'\x00')
# 解码后再去掉中间的空字符
decoded_str = trimmed_byte_data.decode().replace('\x00', '')
print([decoded_str])  # 输出: ['901LHD']

测试验证

把上面的方法放在一起测试:

byte_data = b'901\x00LHD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

# 方法1测试
res1 = byte_data.decode().replace('\x00', '')
print("方法1结果:", [res1])

# 方法2测试
res2 = ''.join(byte_data.decode().split('\x00'))
print("方法2结果:", [res2])

# 方法3测试
trimmed = byte_data.rstrip(b'\x00')
res3 = trimmed.decode().replace('\x00', '')
print("方法3结果:", [res3])

运行后会得到:

方法1结果: ['901LHD']
方法2结果: ['901LHD']
方法3结果: ['901LHD']

内容的提问来源于stack exchange,提问作者Yulia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 09:02:36