bytes-like object code example

Example 1: bytes-like object

#Convert string into byte-like object
newstr = "Hello World"
newstr_bytes = newstr.encode("ascii")
print(newstr_bytes)

Example 2: bytes-like object

#Encoding and Decoding of Base64 step-by-step
# a string that we will convert to bytes
str_string = "Educative"

# convert the string to using bytes with ascii encoding
# parameters of function bytes 
# 1. The string that needs to be converted
# 2. The specified encoding e.g ascii, uft-8 etc.
str_bytes = str_string.encode("ascii")

# Will print the string but as bytes
print("encdoed =    ", str_bytes)

# The type will represent a byte object
print(type(str_bytes))

# represents the ascii encodings of each character in converted string
print(list(str_bytes))

list_bytes = list(str_bytes)

for b in list_bytes:
  print(chr(b), "is represented by",b)

# decoding the string
str_decode = str_bytes.decode("ascii")
print("decoded =    ", str_decode)

Example 3: TypeError: a bytes-like object is required, not 'str'

'Hello World'.encode()