The string is a literal.

3>> bin(int('0b1010', 2))
'0b1010'
3>> bin(int('1010', 2))
'0b1010'
3>> 0b1010
10
3>> int('0b1010', 2)
10
Answer from Ignacio Vazquez-Abrams on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-convert-string-to-binary
Convert String to Binary - Python - GeeksforGeeks
July 12, 2025 - Explanation: converts each character in txt to its 8-bit binary form using ord() and format() then joins them into one binary string using join().
Discussions

python - How to convert string to binary? - Stack Overflow
I am in need of a way to get the binary representation of a string in python. More on stackoverflow.com
๐ŸŒ stackoverflow.com
how do i convert string to binary string and the reverse too?
If you simply want to see the string output in binary, I just do: print(bin(yournumberhere)) More on reddit.com
๐ŸŒ r/learnpython
3
1
October 27, 2022
String to binary
https://www.geeksforgeeks.org/python-convert-string-to-binary/ https://stackoverflow.com/questions/18815820/convert-string-to-binary-in-python https://www.tutorialspoint.com/How-to-convert-string-to-binary-in-Python Google is your friend !!! More on reddit.com
๐ŸŒ r/learnpython
4
1
May 6, 2020
Converting a string which represents binary to binary python - Stack Overflow
I can't quite find a solution for this. Basically what I've done so far is created a string which represents the binary version of x amount of characters padded to show all 8 bits. E.g. if x = ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-convert-string-to-binary-in-python
How to convert string to binary in Python
The string, as seen by the computer, is a binary number that is an ASCCI value( Decimal number) of the string converted to binary.
Top answer
1 of 10
174

Something like this?

>>> 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 of 10
133

If by binary you mean bytes type, you can just use encode method of the string object that encodes your string as a bytes object using the passed encoding type. You just need to make sure you pass a proper encoding to encode function.

In [9]: "hello world".encode('ascii')                                                                                                                                                                       
Out[9]: b'hello world'

In [10]: byte_obj = "hello world".encode('ascii')                                                                                                                                                           

In [11]: byte_obj                                                                                                                                                                                           
Out[11]: b'hello world'

In [12]: byte_obj[0]                                                                                                                                                                                        
Out[12]: 104

Otherwise, if you want them in form of zeros and ones --binary representation-- as a more pythonic way you can first convert your string to byte array then use bin function within map :

>>> st = "hello world"
>>> map(bin,bytearray(st))
['0b1101000', '0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111', '0b1101111', '0b1110010', '0b1101100', '0b1100100']
 

Or you can join it:

>>> ' '.join(map(bin,bytearray(st)))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'

Note that in python3 you need to specify an encoding for bytearray function :

>>> ' '.join(map(bin,bytearray(st,'utf8')))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'

You can also use binascii module in python 2:

>>> import binascii
>>> bin(int(binascii.hexlify(st),16))
'0b110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'

hexlify return the hexadecimal representation of the binary data then you can convert to int by specifying 16 as its base then convert it to binary with bin.

๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ string to binary python
How to Convert a String to Binary in Python | Delft Stack
February 2, 2024 - In Python, a string can be converted to its binary representation using the format(), map(), bytearray(), bin(), and ASCII methods.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-convert-string-to-binary
Python | Convert String to Binary - GeeksforGeeks
May 3, 2023 - 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 code to demonstrate working of # Converting String to binary ...
Find elsewhere
๐ŸŒ
DEV Community
dev.to โ€บ 221910304057vivek โ€บ how-to-convert-string-to-binary-in-python-2igb
How to convert string to binary in python - DEV Community
May 7, 2021 - To convert a string to binary we first append( join ) the string's individual ASCII values to a list l by using the function ord(_string).
๐ŸŒ
Medium
medium.com โ€บ @roscoe.kerby โ€บ understanding-string-to-binary-conversion-in-python-with-a-simple-example-ceddafdee676
Understanding String-to-Binary Conversion in Python with a simple example | by Roscoe Kerby [ROSCODE] | Medium
August 5, 2024 - String-to-Binary conversion involves representing each character in a string as a sequence of binary digits (bits). This process assigns a unique binary code to each character, enabling computers to store and manipulate textual data efficiently.
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ binary-string-to-int-python
Convert Binary String to Int in Python (with code)
September 12, 2023 - ... # initialize a binary string bString = "10101" # conversion value = int(bString, 2) # display the converted value print(value) ... In Python, we may use the bin() function to convert a string to binary.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ How-to-convert-string-to-binary-in-Python
How to convert string to binary in Python?
Here we convert the string into a byte array and apply the bin() function to get binary strings for each byte ?
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ built-in-methods โ€บ convert-binary-string-to-normal-string
4 ways to Convert a Binary String to a Normal String - AskPython
April 23, 2023 - Related: Read this article to know more about the conversion of integers to binary. The bin() function is a built-in Python function used to obtain the binary representation of an integer.
๐ŸŒ
Ars OpenForum
arstechnica.com โ€บ forums โ€บ operating systems & software โ€บ programmer's symposium
Python question: string of binary to an actual binary number | Ars OpenForum
January 7, 2014 - Click to expand... Python makes a pretty nice interactive calculator. You can do the other way around, too, with the builtin function bin(x). (And there are also hex() and oct() builtins, if you also need to go back and forth between base 16- or base 8-represented strings and ints).
๐ŸŒ
Javatpoint
javatpoint.com โ€บ string-to-binary-in-python
String to Binary in Python - Javatpoint
String to Binary in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, operators, etc.
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ built-in-methods โ€บ integer-binary-string-python
Integer to Binary String in Python - AskPython
February 28, 2023 - We can use different functions like a bin(), format(), and other f-strings and string formatting techniques for integer to binary string conversion.
๐ŸŒ
Quora
quora.com โ€บ How-do-you-convert-a-string-to-binary-in-Python
How to convert a string to binary in Python - Quora
Answer (1 of 2): You can convert a string to binary by converting each character to its Unicode representation, then converting it to binary. Let us take an example: [code]>>> s = "hello" [/code]Understanding bin(), ord(): * bin() is an in-built function in Python that takes in integer x and ...
Top answer
1 of 2
2
import struct
with open("foo.bin", 'wb') as f:
    f.write(struct.pack('h', 0b0010010110101))

Will take 2 bytes (16 bits) as a short integer (h). You can define your own format string using the struct module, but I am not sure you will be able to get under the byte size.

EDIT

As per your comment, here's a bit of context:

When writing something in a file, it is always converted to binary. Character are encoded using some rule, called encoding (such as ASCII) where each character is mapped to a number, itself represented in binary. This way, the number 00100100 (36) and the character '$' are the same thing. '$' is represented by 36 on the file, and the software layers between you (such as an editor) will render every '00100100' it encounters as character '$'.

Now when you write the string '00100100' into a file, it will print the characters '0', '1' etc.... So the string '00100100' is represented by the binary number 110000110000110001110000110000110001110000110000. This is necessary because the input being a string, you need an unambiguous way of representing all possible 8-characters long strings, not only the ones representing 0s and 1s.

The Python API for writing files is always writing strings, i.e. it will perform this conversion string -> binary number automatically, and I don't know any way to override that. What you can do however is generate the string such that its binary representation is the actual binary string you wanted to write: if you want to write the number 00100100 in a file, you can just write f.write('$'), which is effectively the same thing.

That is exactly what the 'struct' module performs: it generates a string of bytes, or characters, which exactly match the number you are providing them.

In my example, I give it the number 0b0010010110101, and tell it to encode it as a short integer, i.e. on two bytes. If you execute struct.pack('h', 1205) in the Python interpreter, it will print out the two characters (bytes) \xb5\x04 which correspond to this number in 'byte-base', i.e. base 256 (with big-endian convention). Indeed:

>>> 0x04 * 256 + 0xb5
1205

Just like you can represent any decimal number in base 10 (e.g. 36), base 16 (e.g. 0x24), base 2 (e.g. 0b100100), you can also represent it in base 256 via the ASCII encoding (e.g. '$'). Struct does exactly that, also providing a convenient 'fmt' string convention for the type of data you are writing. You can also do it directly by converting each of your bytes into the corresponding character:

def encode(binary):
    # Aligning on bytes
    binary = '0' * (8 - len(binary) % 8) + binary
    # Generating the corresponding character for each
    # byte encountered
    return ''.join(chr(int('0b' + binary[i:i+8], base = 2)) 
                   for i in xrange(0, len(binary), 8))

This is a very crude and not super efficient way of proceeding, but it does convert every byte into its corresponding character, and returns the corresponding string, which you can directly write into a file:

>>> encode('001001001010100100100100100111110010101110100')
'\x04\x95$\x93\xe5t'

And indeed, writing this to a file produces 6 bytes, corresponding to the 6 characters:

with open("foo.bin", 'wb') as f:
    f.write('\x04\x95$\x93\xe5t')

>>> os.path.getsize("foo.bin")
6L

struct modules performs exactly the same thing, except with a fixed format, and in a more efficient fashion. Instead of getting the chr corresponding to the integer,

def encode2(binary):
    rawbytes = []
    while binary > 0:
        binary, byte = divmod(binary, 256)
        rawbytes.append(byte)
    fmt_string = '%sB' % len(rawbytes)
    print "Encoding %s into %s bytes (%s)" % (rawbytes, len(rawbytes), fmt_string)
    return struct.pack(fmt_string, *rawbytes)

>>> encode2(0b001001001010100100100100100111110010101110100)
Encoding [116L, 229L, 147L, 36L, 149L, 4L] into 6 bytes (6B)
't\xe5\x93$\x95\x04'

(Notice that these are the same character outputted as in encode. The only difference is the order, depending on endianness of the conversion).

You can then decode these character using struct as well, and the same format string:

>>> bytes = struct.unpack('6B', 't\xe5\x93$\x95\x04')
>>> bytes
(116, 229, 147, 36, 149, 4)
>>> bin(sum(x * 256 ** i for i, x in enumerate(bytes)))
'0b1001001010100100100100100111110010101110100'

Which is our original number.

Bottom line is: Python file API can only process characters, which are effectively bytes. There might be some magic way of writing individual bits to a file, but I wouldn't count too much on that, as this introduces its own world of problems, and bytes are more than sufficient in 99% of cases. To write binary data, represent it in base 256, and convert each of its b256 digits to the corresponding character. The binary representation of this string is, by definition, your original number.

2 of 2
0

binascii can be used.

import binascii

a = "1010"
b = "10"
c = "00"

data = a + b + c
hex_string = hex(int(data, 2))[2:]  #remove '0x'

with open('foo', 'wb') as f:
    f.write(binascii.unhexlify(hex_string))

The hex_string should be even, so you need to add one bit to "0010010110101" to make unhexlify work properly.

๐ŸŒ
YouTube
youtube.com โ€บ watch
Convert Text To Binary in Python - YouTube
Today we learn how to convert text to binary and back in Python.โ—พโ—พโ—พโ—พโ—พโ—พโ—พโ—พโ—พโ—พโ—พโ—พโ—พโ—พโ—พโ—พโ—พ๐Ÿ“š Programming Books & Merch ๐Ÿ“š๐Ÿ The Python Bible Book: https://www.neuraln...
Published: October 30, 2022