Python | Convert String to Binary

Data conversion have always been widely used utility and one among them can be conversion of a string to it’s binary equivalent. Let’s discuss certain ways in which this can be done.

Method #1 : Using join() + ord() + format()
The combination of above functions can be used to perform this particular task. The ord function converts the character to it’s ASCII equivalent, format converts this to binary number and join is used to join each converted character to form a string.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Converting String to binary
# Using join() + ord() + format()
  
# initializing string 
test_str = "GeeksforGeeks"
  
# printing original string 
print("The original string is : " + str(test_str))
  
# using join() + ord() + format()
# Converting String to binary
res = ''.join(format(ord(i), 'b') for i in test_str)
  
# printing result 
print("The string after binary conversion : " + str(res))

chevron_right


Output :



The original string is : GeeksforGeeks
The string after binary conversion : 1000111110010111001011101011111001111001101101111111001010001111100101110010111010111110011

 

Method #2 : Using join() + bytearray() + format()
This method is almost similar to the above function. The difference here is that rather than converting the character to it’s ASCII using ord function, the conversion at once of string is done by bytearray function.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Converting String to binary
# Using join() + bytearray() + format()
  
# initializing string 
test_str = "GeeksforGeeks"
  
# printing original string 
print("The original string is : " + str(test_str))
  
# using join() + bytearray() + format()
# Converting String to binary
res = ''.join(format(i, 'b') for i in bytearray(test_str, encoding ='utf-8'))
  
# printing result 
print("The string after binary conversion : " + str(res))

chevron_right


Output :

The original string is : GeeksforGeeks
The string after binary conversion : 1000111110010111001011101011111001111001101101111111001010001111100101110010111010111110011


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.