user31172
0
Q:

convert string to binary python

>>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'
2
# 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)) 
3

New to Communities?

Join the community