How to decode the byte into string in python3

After receiving the bytes from Server, it needs to convert into string. When I try below code, not works per expected.

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'

Upvotes: 0

Views: 585

Answers (1)

Arminius
Arminius

Reputation: 1169

This is not an encoding issue, as the trailing bytes are all NUL bytes. Looks like your server is padding with Null bytes. To remove them just use

a.strip(b'\x00')

Upvotes: 2

Related Questions