How To Split A Binary String In Python

In this tutorial, we will learn how to split a given binary string in Python. A binary string is comprised of characters like 0 and 1 and can be represented in Python as a string. Splitting binary string can be performed using many ways. Here we will focus on using built-in string functions like split() and re.split().

Using split() Function

The string split() function can be used to split a string based on a specific delimiter. By default, it separates a given string using whitespace as a delimiter.

To split the binary string, you can set the desired delimiter as a parameter for the split() function.

Here, the binary string is separated at each “-“.

Using re.split()

Another approach to split a binary string is by using the re.split() function from the re module. This provides more flexibility when it comes to splitting the string.

In this example, we use a regular expression to define the delimiter character. The string will be split by two different types of delimiters, a hyphen, and an underscore.

Full Code


Using split() function: ['1010', '1101', '0101']
Using re.split(): ['1010', '1101', '0101']


In this tutorial, we learned how to split a binary string in Python using the built-in split() function and the re.split() function. Both methods can be useful depending on the level of complexity and flexibility required in splitting the string. The choice between these methods ultimately depends on the needs and requirements of your specific project.