bytes()

Convetring to bytes object.
bytes(object,encoding='utf-8',errors='strict')
object : ( Required ) The object which is to be coverted
encoding : ( Optional ) default is 'utf-8'
errors : ( Optional ) what to do if error occurs.
Returns an immutable array of bytes.
The bytes object consist of sequnce of integer in the range of 0<=x<=256

Using an integer

my_int=5
my_bytes = bytes(my_int)
print(my_bytes) #   b'\x00\x00\x00\x00\x00'

Using string

For string argument, we need to give encoding type.
my_str = "plus2net.com"
my_bytes = bytes(my_str, encoding='utf-8')
print(my_bytes) #  b'plus2net.com'
print(type(my_bytes)) # <class 'bytes'>
Using iterable
my_list=[1,2,3,4]
my_bytes=bytes(my_list)
print(my_bytes) #  b'\x01\x02\x03\x04'

Using errors

This code will generate UnicodeEncodeError:
my_str="plus2net.cÖm"
my_bytes = bytes(my_str, encoding='ascii',errors='strict')
print(my_bytes) 
We can keep errors='ignore' to silent the error and continue execution
my_str="plus2net.cÖm"
my_bytes = bytes(my_str, encoding='ascii',errors='ignore')
print(my_bytes) #  b'plus2net.cm'
We can set errors = 'replace'
my_str="plus2net.cÖm"
my_bytes = bytes(my_str, encoding='ascii',errors='replace')
print(my_bytes) # b'plus2net.cm' #  b'plus2net.c?m'
using fromhex() method we can use hex value inputs.
mybytes=bytes.fromhex('F1F1')
print(mybytes) # b'\xf1\xf1'




plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer