2017-08-24 74 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') 
相關問題