Skip to main content

How to convert a string to binary in Python

How to convert a string to binary in Python.

Here's a detailed step-by-step tutorial on how to convert a string to binary in Python:

Step 1: Start by defining a string that you want to convert to binary. For example, let's say we have the string "Hello World!". You can declare it as follows:

string = "Hello World!"

Step 2: Iterate through each character in the string. To do this, you can use a for loop. We'll create an empty list called binary_list to store the binary representations of each character:

binary_list = []
for char in string:

Step 3: Convert each character to its binary representation. In Python, you can use the built-in ord() function to get the Unicode code point of a character, and then use the bin() function to convert it to binary. We'll append each binary representation to the binary_list:

    binary_list.append(bin(ord(char)))

Step 4: Remove the prefix "0b" from each binary representation. The bin() function in Python adds the prefix "0b" to indicate that the string is in binary format. To remove it, we can use string slicing:

    binary_list.append(bin(ord(char))[2:])

Step 5: Join all the binary representations together to form a single binary string. We can use the join() method and pass the binary_list as an argument:

binary_string = ''.join(binary_list)

Step 6: Print the final binary string:

print(binary_string)

Now, let's put all the steps together:

string = "Hello World!"
binary_list = []
for char in string:
binary_list.append(bin(ord(char))[2:])
binary_string = ''.join(binary_list)
print(binary_string)

When you run this code, the output will be:

100100011001011101100110110011011111000001011101011110111001001101100011001000100001

That's it! You have successfully converted a string to binary in Python.