Change language

Python | Convert string to bytes

| |

Method # 1: Using bytes (str, enc)

A string can be converted to bytes using the generic byte function. This function internally points to the CPython library, which implicitly calls the encoding function to convert the string to the specified encoding.

Exit: < / b>

 The original string: GFG is best The byte converted string is: b’GFG is best’, type: "class ’bytes’" 

Method # 2: Using encode(enc)

The most recommended method to accomplish this particular task, using a coding function to perform the transformation, since it minifies one additional reference to a specific library, this function calls it directly.

# Python code for demonstration
# convert string to byte
# Use bytes (str, enc)

 
# initialization string

test_string = "GFG is best"

  
# print the original line

print ( "The original string:" + str ( test_string))

 
# Using bytes (str, enc)
# convert string to byte

res = bytes (test_string, ’utf-8’ )

 
# print result

print ( "The byte converted string is :" + str (res) + ", type:" + str ( type (res)))

# Python code for demonstration
# convert string to byte
# Use encoding (enc)

 
# initialization string

test_string = "GFG is best"

 
# print original line

print ( " The original string: " + str (test_string))

  
# Using encoding
# convert string to byte

res = test_string.encode ( ’utf-8’ )

  
# print result

print ( " The byte converted string is : " + str ( res) + ", type:" +   str ( type (res) ))

Output:

 The original string: GFG is best The byte converted string is: b’GFG is best’, type: "class ’bytes’"