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