Sometimes in Python, you might come across a string that looks like "101010" just a bunch of 1s and 0s.
It looks like binary, but Python treats it as plain text. If you want to use that value as a binary number, for example, to do some math or comparisons, you’ll need to convert it first.
I will explain to you some important methods to convert a string of 1s and 0s to binary in Python, along with examples.
Convert String of 1s and 0s to Binary in Python
Before getting into the code, let’s clarify what we’re trying to accomplish. When we have a string like “01101101”, it’s just a string of characters that happen to be 1s and 0s. It doesn’t inherently have any binary value properties in Python.
What we want is to convert this string into an actual binary value that Python recognizes as a number (specifically, a binary representation of a number).
Read How to Print Strings and Variables in Python?
Method 1: Use the int() Function with Base 2
The most simple and commonly used approach is to use Python’s built-in int() function with a base parameter of 2.
# Converting a binary string to an integer
binary_string = "01101101"
binary_value = int(binary_string, 2)
print(f"Binary string: {binary_string}")
print(f"Integer value: {binary_value}")
print(f"Binary representation: {bin(binary_value)}")Output:
Binary string: 01101101
Integer value: 109
Binary representation: 0b1101101I executed the above example code and added the screenshot below.

This method is simple and effective for most use cases. The second parameter of int() specifies the base of the number represented by the string.
When to Use This Method
- When you need a quick conversion from a binary string to its integer value
- When working with numerical operations on binary-represented data
- When the binary strings aren’t excessively long
Check out How to Convert a String to a Float in Python?
Method 2: Use Binary Literals
If you already have a binary string made of 1s and 0s, Python lets you easily convert it into a number using int() with base 2.
# Using the result in a calculation
binary_string = "01101101"
binary_value = int(binary_string, 2)
# Performing operations with the binary value
result = binary_value * 2
print(f"Result of binary_value * 2: {result}")
print(f"In binary: {bin(result)}")Output:
Result of binary_value * 2: 218
In binary: 0b11011010I executed the above example code and added the screenshot below.

Once converted, you can do regular math with it, and even get the result back in binary using bin().
Read How to Remove Spaces from String in Python?
Method 3: Handle Binary Strings with Leading Zeros
Sometimes when you convert a binary string to a number in Python, it drops the leading zeros. This can be a problem if you want to keep the original format.
binary_string = "00101101"
binary_value = int(binary_string, 2)
# Standard binary representation (loses leading zeros)
standard_repr = bin(binary_value)
print(f"Standard binary: {standard_repr}")
# Preserved format (keeping leading zeros)
preserved_format = '0b' + binary_string
print(f"Preserved format: {preserved_format}")Output:
Standard binary: 0b101101
Preserved format: 0b00101101I executed the above example code and added the screenshot below.

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?
Method 4: Convert Larger Binary Strings
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:]}")Rather than printing the full value, you can explore its properties, like how many bits it uses, or check just the beginning and end of the binary to keep things simple and readable.
Read How to Pad Strings with Spaces in Python?
Method 5: Work with Binary Data in Files
When dealing with files in Python, you might come across situations where you need to write or read binary data—like saving binary strings or processing raw data from a file.
# Writing binary data to a file
binary_string = "01101101"
binary_value = int(binary_string, 2)
with open("binary_data.bin", "wb") as binary_file:
# Convert to bytes and write
binary_file.write(binary_value.to_bytes((binary_value.bit_length() + 7) // 8, 'big'))
# Reading binary data from a file
with open("binary_data.bin", "rb") as binary_file:
data = binary_file.read()
# Convert bytes back to integer
value = int.from_bytes(data, 'big')
# Convert integer to binary string
recovered_string = bin(value)[2:].zfill(8)
print(f"Recovered binary string: {recovered_string}")Using to_bytes() and from_bytes() you can easily convert between binary strings and byte data, making it simple to store and retrieve binary information from files.
Check out How to Convert Bytes to Strings in Python?
Common Use Cases for Binary String Conversion in Python
Now I will explain the common use cases for binary string conversion in Python.
1. Data Encoding and Decoding
When you want to send text over a network or store it in a low-level format, converting it to binary is often the first step.
# ASCII encoding example
def text_to_binary(text):
binary = ""
for char in text:
# Convert each character to its ASCII value, then to binary
ascii_val = ord(char)
binary_char = bin(ascii_val)[2:].zfill(8)
binary += binary_char + " "
return binary
def binary_to_text(binary):
binary_values = binary.split()
text = ""
for binary_val in binary_values:
# Convert each binary value to its decimal value, then to character
decimal_val = int(binary_val, 2)
text += chr(decimal_val)
return text
# Example usage
message = "Hello"
binary_message = text_to_binary(message)
print(f"Text to binary: {binary_message}")
decoded_message = binary_to_text(binary_message)
print(f"Binary to text: {decoded_message}")By converting text to binary and back, you ensure that your data can be transmitted, stored, or processed correctly across different systems and platforms.
Read How to Split a String into Characters in Python?
2. Working with Bitwise Operations
Bitwise operations allow you to work directly with the binary form of numbers, which is useful in low-level programming, encryption, and performance optimization.
# Bitwise operations on binary values
binary_string1 = "10101010"
binary_string2 = "11110000"
value1 = int(binary_string1, 2)
value2 = int(binary_string2, 2)
# Perform bitwise AND
result_and = value1 & value2
print(f"AND result: {bin(result_and)[2:].zfill(8)}")
# Perform bitwise OR
result_or = value1 | value2
print(f"OR result: {bin(result_or)[2:].zfill(8)}")
# Perform bitwise XOR
result_xor = value1 ^ value2
print(f"XOR result: {bin(result_xor)[2:].zfill(8)}")Binary string conversion makes it easy to perform bitwise operations like AND, OR, and XOR, helping you manipulate data more efficiently at the bit level.
Check out How to Convert String to UTF-8 in Python
Troubleshoot Common Issues that Occur During the Binary String Conversion in Python
Let me explain how to troubleshoot common issues that occur during the binary string conversion in Python.
Invalid Literal Error
Sometimes when converting a string to binary, you might get an “invalid literal” error. This usually happens when the string includes characters other than 0 and 1.
try:
invalid_binary = "01201"
value = int(invalid_binary, 2)
except ValueError as e:
print(f"Error: {e}")
# Correct approach - validate the string first
if all(bit in '01' for bit in invalid_binary):
value = int(invalid_binary, 2)
else:
print("String contains non-binary characters.")To avoid this error, always check if the string contains only binary digits before converting.
Read How to Concatenate String and Int in Python?
Issues with MicroPython
MicroPython doesn’t support all the string formatting methods that standard Python does, so converting text to binary may need a slightly different approach.
# In standard Python, this works:
binary_string = ''.join(format(ord(char), '08b') for char in "Hello")
# In MicroPython, use this alternative:
def to_binary(text):
result = ""
for char in text:
binary = bin(ord(char))[2:]
binary = '0' * (8 - len(binary)) + binary # Zero padding
result += binary
return resultIf you’re working in MicroPython, stick to basic string manipulation and padding to handle binary conversions safely and reliably.
Related article, you may like to read:
- How to Split String by Whitespace in Python?
- How to Repeat a String Multiple Times in Python?
- How to Convert Datetime to String in Python?

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.