Byte Objects vs Strings in Python

In Python 2, both str and bytes are the same typeByte objects, whereas in Python 3, byte objects defined in Python 3 are “ byte sequences ” and are similar to “ unicode “from Python 2. However, there are many differences in strings and Byte objects. Some of them are shown below:
`

  • Byte objects — it is a sequence of bytes , and the lines — it is a sequence of characters .
  • Internal byte objects are in machine-readable form, lines — in human readable form only.
  • Because byte objects are machine readable, they can be directly stored on disk . Whereas strings need to be encoded before which they can be saved to disk.

There are methods to convert a byte object to String and String to byte objects.

encoding

PNG, JPEG, MP3, WAV, ASCII, UTF-8, etc. are different forms of encoding. Encoding — it is a format for representing audio, images, text, etc. in bytes. Converting strings to byte objects is called encoding. This is necessary so that the text can be saved to disk using matching using ASCII or UTF-8 encoding techniques.

This task is accomplished with using encode () . The coding technique is used as an argument. The default is UTF-8 .

# Python code to dismantle the String

 
# line initialization

a = `GeeksforGeeks`

  
# initializing the byte object

c = b `GeeksforGeeks`

  
# using encode () to encode the string
# the encoded version of a is stored in d
# using ASCII display

d = a.encode ( `ASCII` )

 
# check if it`s converted a to bytes or not

if (d = = c):

print ( "Encoding successful" )

else : print ( "Encoding Unsuccessful" )

Output:

 Encoding successful 

Decoding

Similarly, Decoding — it is a process for converting a Byte object to String . This is implemented using decode () . A byte string can be decoded back into a character string if you know what encoding was used to encode it. Encoding and decoding are reverse processes.

# Python code to remove byte decoding

 
# line initialization

a = `GeeksforGeeks`

  
# initializing the byte object

c = b `GeeksforGeeks`

  
# using decode () to decode the Byte object
# the decoded version of c is stored in d
# using mapped iya ASCII

d = c.decode ( `ASCII` )

  
# check if c is converted to a string or not

if (d = = a):

print ( "Decoding successful" )

else : print ( "Decoding Unsuccessful" )

Output:

 Decoding successful 

This article contributed by Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.