Monday 29 November 2021

Python: bytes(): get immutable bytes object

‘bytes’ method take an object and return an immutable bytes object.

 

Signature

bytes([source[, encoding[, errors]]])

 

Example

byte_message1 = bytes(message, 'utf-8')

 

bytes_demo_1.py

message = 'Hello World'

# convert string to bytes
byte_message1 = bytes(message, 'utf-8')
byte_message2 = bytes(message, 'utf-16')
byte_message3 = bytes(message, 'utf-32')

print('byte_message1 -> ', byte_message1, 'len(byte_message1) ' , len(byte_message1))
print('byte_message2 -> ', byte_message2, 'len(byte_message2) ' , len(byte_message2))
print('byte_message3 -> ', byte_message3, 'len(byte_message3) ' , len(byte_message3))

 

Output

byte_message1 ->  b'Hello World' len(byte_message1)  11
byte_message2 ->  b'\xff\xfeH\x00e\x00l\x00l\x00o\x00 \x00W\x00o\x00r\x00l\x00d\x00' len(byte_message2)  24
byte_message3 ->  b'\xff\xfe\x00\x00H\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00 \x00\x00\x00W\x00\x00\x00o\x00\x00\x00r\x00\x00\x00l\x00\x00\x00d\x00\x00\x00' len(byte_message3)  48

 

Convert a list to bytes

 

bytes_demo_2.py

message = [2, 3, 5, 7]

byte_message1 = bytes(message)

print('byte_message1 -> ', byte_message1, 'len(byte_message1) ' , len(byte_message1))

 

Output

byte_message1 ->  b'\x02\x03\x05\x07' len(byte_message1)  4

 


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment