Change language

Python | Convert string to binary

|

Method # 1: Using join () + ord () + format ()
A combination of the above functions can be used to accomplish this particular task. The ord function converts a character to its ASCII equivalent, the format converts it to binary, and join is used to concatenate each converted character into a string.

# Python3 code for demonstrations
# Convert string to binary
# Using join () + ord () + format ()

 
# initialization string

test_str = "GeeksforGeeks"

 
# print the original line

print ( "The original string is:" + str (test_str))

  
# using join () + ord () + format ()
# Convert string to binary

res = ’.join (format (ord (i),’ b’) for i in test_str)

 
# print result

print ( "The string after binary conversion:" + str (res))

Output:

 The origi nal string is: Python.Engineering The string after binary conversion: 10001111100101110010111010111110011001101101111111001010001111100101110010111010111110011 

Method # 2: Using join () + bytearray () + format () / strong>
This method is almost the same as the above function. The difference here is that instead of converting the character to its ASCII using the ord function, the conversion to the string is performed immediately by the bytearray function.

# Python3 code to demonstrate how it works
# Convert string to binary
# Using join () + bytearray () + format ()

 
# initialization string

test_str = "GeeksforGeeks"

 
# print original line

print ( "The original string is:" + str (test_str))

 
# using join () + bytearray () + format ()
# Convert string to binary

res = ’.join (format (i,’ b ’) for i in bytearray (test_str, encoding =’ utf - 8 ’) )

 
# print result

print ( "The string after binary conversion:" + str (res))

< p>
Output:

 The original string is: Python.Engineering The string after binary conversion: 1000111110010111001011101011111001111001101101111111001010001111100101110010111010111110011 

Python | Convert string to binary Python functions: Questions

Python | Convert string to binary String Variables: 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