Try this:

int(s, base=2)

for example,

for i in ['10101', '11100', '11010', '00101']:
    print(int(i, base=2))

@metatoaster also mentioned this.

Answer from 0__ on Stack Overflow
🌐
Python Guides
pythonguides.com › convert-string-of-1s-and-0s-to-binary-in-python
Convert String Of 1s And 0s To Binary In Python
May 16, 2025 - To keep those leading zeros, you can manually add '0b' in front of the original string instead of depending on Python’s built-in bin() function. Check out How to Count Characters in a String in Python? Even if you’re working with really large binary strings, Python can still handle them efficiently using the int() function to convert them. # Large binary string large_binary = "1" * 1000 + "0" * 1000 # Using int() is still efficient for large strings in Python large_value = int(large_binary, 2) # Instead of printing the entire number, let's check its properties print(f"Number of bits: {large_value.bit_length()}") print(f"First few digits: {bin(large_value)[2:10]}...") print(f"Last few digits: ...{bin(large_value)[-8:]}")
Discussions

How do I convert a string of 1's and 0's to bits in the huffman compression algorithm?
Does the binascii module do what you want? https://docs.python.org/3/library/binascii.html More on reddit.com
🌐 r/learnpython
9
15
March 14, 2018
python - Is there a way of converting a string of 1's and 0's to its binary counterpart, i.e. not ASCII - Stack Overflow
In Python I have learnt that creating ints like 0b01101101 will create a binary literal. Say I have a string data type of "01101101" is there a way to convert this to a binary literal? The example More on stackoverflow.com
🌐 stackoverflow.com
python - Turning binary data into a literal string of '0's and '1's - Stack Overflow
I have a file filled with binary data representing a sequence of 2 byte instructions in big endian ordering. I need to be able to decode these instructions into their more meaningful equivalents, ... More on stackoverflow.com
🌐 stackoverflow.com
October 5, 2015
Python: String of 1s and 0s -> binary file - Stack Overflow
I have a string of 1's and 0's in Python and I would like to write it to a binary file. I'm having a lot of trouble with finding a good way to do this. Is there a standard way to do this that I'm ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python Forum
python-forum.io › thread-2755.html
HELP: String of Zero's and One's to binary byte
April 7, 2017 - I have some code that I am using to convert a file to bytes then those bytes to strings of 0's and 1's. with open(file, mode='rb') as file: content = file.read() b = bytearray(content) for number in b: data = bin(number)[2:].zfill(8) prin...
Top answer
1 of 2
4

You could convert b'a' to its corresponding integer ord value, and then print the int in binary format using '{:b}'.format:

In [6]: '{:b}'.format(ord(b'a'))
Out[6]: '1100001'

  • Reading a large file one-byte-at-a-time can be very slow. You'll get better performance by reading more bytes per call to f.read. You can iterate over the contents of the file in chunks of 1024 bytes using:

    with open(filename, 'rb') as f:
        for chunk in iter(lambda: f.read(1024), b''):
    
  • Similarly, calling print once for each byte can be very slow. You'll get better performance by printing more bytes per call to print. So you could use a list comprehension to loop over the bytes in chunk, convert each to its string-binary format and then use ''.join to join the strings together:

    print(''.join(['{:b}'.format(ord(c)) for c in chunk]), end='')
    
  • Use bare except is considered a bad practice. If you choose to use try..except here, list only those Exceptions you wish to handle:

    try:
        ...
    except IOError:          
    

def slurpInstructions(filename):
    with open(filename, 'rb') as f:
        for chunk in iter(lambda: f.read(1024), b''):
            print(''.join(['{:b}'.format(c) for c in chunk]), end='')
2 of 2
2

In Python 3, to convert 2 bytes into a bitstring ('{:b}'.format() may be slightly slower):

>>> bin(int.from_bytes(b'\x00a', 'big'))[2:].zfill(16)
'0000000001100001'

For a single-source Python 2/3 compatible version, see Convert binary to ASCII and vice versa

To load all instructions both time- and space-efficiently, you could use array module:

#!/usr/bin/env python
import os
import sys
from array import array

instructions = array('H') # each instruction is >=2 bytes   
n = os.path.getsize(filename) // instructions.itemsize # number of instructions
with open(filename, 'rb') as file:
    instructions.fromfile(file, n) # slurp file
if sys.byteorder == 'little':
    instructions.byteswap() # force big-endian order

for h in instructions: # print as bitstrings
    print('{:016b}'.format(h))

For other ways to read a binary file efficiently, see Reading binary file in Python and looping over each byte.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-string-to-binary
Convert String to Binary - Python - GeeksforGeeks
July 12, 2025 - bin(int(..., 16))[2:] converts the hex string to binary, removing the '0b' prefix
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › [micropython] convert a string to binary 1s and 0s.
r/learnpython on Reddit: [Micropython] Convert a string to binary 1s and 0s.
January 13, 2022 -

Let's say I input a as my variable. I want it to display 01100001

That's it. I've tried everything but for some reason micropython shits itself when I try to use conversion_binary = ''.join(format(ord(i), '08b') for i in lett)"

And yet normal Python works just fine. I don't get it. It just says that "format" isn't defined.

🌐
Educative
educative.io › answers › how-to-convert-string-to-binary-in-python
How to convert string to binary in Python
Strings are an array of Unicode code characters. Binary is a base-2 number system consisting of 0’s and 1’s that computers understand.
🌐
GeeksforGeeks
geeksforgeeks.org › python-convert-string-to-binary
Python | Convert String to Binary - GeeksforGeeks
May 3, 2023 - There are multiple approaches by which this conversion can be performed that are illustrated below: Method 1: By using binascii module Binascii helps convert between binary and various ASCII-en · 3 min read Python Program to Generate Random ...
🌐
Stack Overflow
stackoverflow.com › questions › 33130436 › interpret-a-string-made-of-0-and-1-as-a-binary-sequence
python - interpret a string made of 0 and 1 as a binary sequence? - Stack Overflow
Using python, I want to convert/interpret a string made of 0 and 1 as if it was binary. Assume I have a string that looks like this: >>>str = "
🌐
Finxter
blog.finxter.com › home › learn python blog › how to convert a string to binary in python
How to Convert a String to Binary in Python - Be on the Right Side of Change
October 29, 2022 - Python’s built-in bin(integer) function takes one integer argument and returns a binary string with prefix "0b". If you call bin(x) on a non-integer x, it must define the __index__() method that returns an integer associated to x.
🌐
YouTube
youtube.com › watch
How to Convert a String to Binary in Python? - YouTube
Full Tutorial: https://blog.finxter.com/how-to-convert-a-string-to-binary-in-python/==========================================You can convert a string to bin...
Published: June 1, 2022
🌐
Reddit
reddit.com › r/learnpython › how can i convert a file into a string of 1s and 0s?
r/learnpython on Reddit: How can I convert a file into a string of 1s and 0s?
March 24, 2022 -

I want to write a function that takes the path of a file and returns a string of 1s and 0s that can later be converted back into the original file. I've tried using the base64 module on an image file, but it gives me a string full of weird symbols, like what you would see if you opened the image in a text editor.

with open(file_path, "rb") as contents:
    converted_string = base64.b64encode(contents.read())
    print(converted_string)

I want only 1s and 0s. How can I do so?

Edit: Making my question clearer.

🌐
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 - The function ord(_string) gives the ASCII value of the string. i.e ord(H) = 72 , ord(e) = 101. Then from the list of ASCII values we convert them to binary by using the function bin(_integer).
🌐
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.