2017-08-24 70 views
0

从Server接收到字节后,需要将其转换为字符串。当我尝试下面的代码时,不符合预期。如何在python3中将字节解码为字符串

a 
Out[140]: b'NC\x00\x00\x00' 

a.decode() 
Out[141]: 'NC\x00\x00\x00' 

a.decode('ascii') 
Out[142]: 'NC\x00\x00\x00' 

a.decode('ascii').strip() 
Out[143]: 'NC\x00\x00\x00' 

a.decode('utf-8').strip() 
Out[147]: 'NC\x00\x00\x00' 

# I need the Output as 'NC' 

回答

1

这不是一个编码问题,因为尾随字节都是NUL字节。看起来你的服务器正在填充空字节。删除它们只是使用

a.strip(b'\x00') 
相关问题