Binary codes (binary, binary numbers, or binary literals) are a way of representing information using only two symbols: 0 and 1. They are like a secret language that computers are able to understand. By combining these symbols in different patterns, we can represent numbers, letters, and other data.
This concise, example-based article will walk you through 3 different approaches to turning a given string into binary in Python.
Using the ord() function and string formatting
What we’ll do are:
- Loop through each character in the string.
- Convert each character to its corresponding Unicode code using the
ord()
function. - Convert the Unicode code to binary using the
format()
function with a format specifier. - Concatenate the binary codes to form the final binary string.
Code example:
input = "Sling Academy"
binary_codes = ' '.join(format(ord(c), 'b') for c in input)
print(binary_codes)
Output:
1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001
Using the bytearray() function
Here’re the steps:
- Convert the string to a bytearray object, which represents the string as a sequence of bytes.
- Iterate over each byte in the bytearray.
- Convert each byte to binary using the
format()
function with a format specifier. - Concatenate the binary codes to form the final binary string.
Code example:
my_string = "Sling Academy"
byte_array = bytearray(my_string, encoding='utf-8')
binary_codes = ' '.join(bin(b)[2:] for b in byte_array)
print(binary_codes)
Output:
1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001
Using the bin() and ord() functions
This technique can be explained as follows:
- Iterate over each character in the string.
- Convert each character to its corresponding Unicode code using the
ord()
function. - Use the
bin()
function to convert the Unicode code to binary. - Remove the leading
0b
prefix from each binary code. - Concatenate the binary codes to form the final binary string.
Thanks to Python’s concise syntax, our code is very succinct:
text = "Sling Academy"
binary_string = ' '.join(bin(ord(char))[2:] for char in text)
print(binary_string)
Output:
1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001
Conclusion
You’ve learned some methods to transform a given string into binary in Python. All of them are neat and delicate. Choose the one you like to go with. Happy coding & have a nice day!