- How to convert string to binary in Python(4 ways)
- 1. Using ord(),format() to convert string to binary
- Python Program to Convert string to binary in Python
- Python Program to convert string to binary in Python
- 3. Map() to convert string to binary in Python
- Python Program to convert string to binary in Python
- 4. Math Module,ord(),bin() to convert string to binary
- Python Program to convert string to binary
- Summary
- Python | Convert String to Binary
- Python3
- Python3
- String to Bits
- Python: 3 Ways to Convert a String to Binary Codes
- Using the ord() function and string formatting
- Using the bytearray() function
- Using the bin() and ord() functions
- Conclusion
How to convert string to binary in Python(4 ways)
In this post,we are going to learn how to convert string to binary in Python with examples using built in function join() ,ord() ,format() and bytearray(),map(),bin() and Math module.
1. Using ord(),format() to convert string to binary
In this example, we are using three functions join(), ord(), format() to convert string to its binary representation and for loop to iterate over each character of the string, format() function to insert a value between placeholder finally using join() function to concatenate the element by space delimiter.
- ord() : This function returns the number representing the unicode of given character. It takes a string as an argument and returns its unicode
- format() : The format() function format the given value and insert the value between the placeholder.
- Join() : The join() method concatenate the elements by delimiter.
Python Program to Convert string to binary in Python
- val: The number that we want to convert into binary string
- Format : It convert the passed value to given format.
The join() function concatenate the element by space delimiter. Let us understand with an example.
Python Program to convert string to binary in Python
In this example, we have defined a custom method str_binary() that takes a string as an argument and returns binary representation.
def str_binary(Str): binaryStr = ' '.join(format(i, '08b') for i in bytearray(Str, encoding ='utf-8')) print(binaryStr) Str = "Good Morning" str_binary(Str)
01000111 01101111 01101111 01100100 00100000 01001101 01101111 01110010 01101110 01101001 01101110 01100111
3. Map() to convert string to binary in Python
In this example, we are using the bytearray that returns an array of the byte in our example its returns an array of bytes for a given string “str”, using map() along with bin() to get the binary of given string.
Python Program to convert string to binary in Python
def str_binary(Str): binaryStr = ' '.join(map(bin, bytearray(Str, encoding ='utf-8'))) print(bytearray(Str, encoding ='utf-8')) print(binaryStr) Str = "Good Morning" str_binary(Str)
0b1000111 0b1101111 0b1101111 0b1100100 0b100000 0b1001101 0b1101111 0b1110010 0b1101110 0b1101001 0b1101110 0b1100111
4. Math Module,ord(),bin() to convert string to binary
In this example we have defined a custom function name “Strto_Binary” first, we are using ord() to get numbers that represent Unicode of given characters in a string and append them to a list.
In the second step, we are using bin() to get the binary value of each character and [2:] to remove the prefix “0b” and appending them to result in the list(mod_list) and return the result list. We are calling the custom function “Strto_Binary” bypassing the string that we want to convert into binary.
Python Program to convert string to binary
def Strto_Binary(str): list,mod_list=[],[] for item in Str: list.append(ord(item)) for item in list: mod_list.append(int(bin(item)[2:])) return mod_list print(Strto_Binary("Good Morning"))
[1000111, 1101111, 1101111, 1100100, 100000, 1001101, 1101111, 1110010, 1101110, 1101001, 1101110, 1100111]
Summary
In this post, we have learned how to convert string to binary in Python with code example by using built in function join() ,ord() ,format() and bytearray(),map(),bin() and Math module.
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.
Python3
The original string is : GeeksforGeeks The string after binary conversion : 01000111011001010110010101101011011100110110011001101111011100100100011101100101011001010110101101110011
Time Complexity: O(N) where N is the lenght of the input string.
Auxiliary Space: O(N)
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.
Python3
The original string is : GeeksforGeeks The string after binary conversion : 01000111011001010110010101101011011100110110011001101111011100100100011101100101011001010110101101110011
Method #3 : Using join() + bin() + zfill()
we define a function str_to_binary(string) that takes in a string as its input.
We then create an empty list called binary_list, which will be used to store the binary conversions of each character in the input string.
We then use a for loop to iterate through each character in the input string. For each character, we use the ord() function to convert it to its ASCII equivalent, and then use the bin() function to convert that integer to a binary string. The bin() function returns a string with a ‘0b’ prefix, so we use list slicing to remove that prefix.
After that we use the zfill(8) method to pad the binary conversion with leading zeroes until it reaches a length of 8. The zfill() method pads the string on the left with a specified character (in this case, ‘0’) until it reaches the desired length.
Then we append the binary conversion to the binary_list and after that we join all the binary values in the list and return as a single string by using join() method.
Finally, we test the function with an example input of the string “GeeksforGeeks”. The function returns the binary string representation of the input string.
String to Bits
This snippet defines a function a2bits which converts a characters string to a string of 0’s and 1’s showing its bitwise representation.
import sys if sys.version_info[0] >= 3: bin = "".format from functools import reduce def a2bits(chars): "Convert a string to its bits representation as a string of 0's and 1's" return bin(reduce(lambda x, y : (x<<8)+y, (ord(c) for c in chars), 1))[3:]
from binascii import hexlify def a2bits(bytes): """Convert a sequence of bytes to its bits representation as a string of 0's and 1's This function needs python >= 2.6""" return bin(int(b"1" + hexlify(bytes), 16))[3:]
Another possibility is to use a specialized module to handle binary data. One such module is bitstring (http://pypi.python.org/pypi/bitstring). Install it with easy_install or pip. Example:
>>> from bitstring import BitString >>> bs = BitString(bytes="hello world") >>> bs BitStream('0x68656c6c6f20776f726c64') >>> bs.bin '0b0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Reach out to all the awesome people in our software development community by starting your own topic. We equally welcome both specific questions as well as open-ended discussions.
Python: 3 Ways to Convert a String to Binary Codes
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
- 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.
input = "Sling Academy" binary_codes = ' '.join(format(ord(c), 'b') for c in input) print(binary_codes)
1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001
Using the bytearray() function
- 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.
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)
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)
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!