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’" 

Python | Convert string to bytes convert string to bytes: Questions

Python | Convert string to bytes Python functions: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method