Bitwise XOR Operation Between Binary Strings in Python

In this programming example, we take two binary strings and compute bitwise XOR operation between the strings using Python. If the given strings are unequal in length then we first make them equal by prepending 0s in the string with lesser length.

Python Source Code


# bitwise OR operation between two binary strings in python

def make_string_equal_length(a, b):
    len1 = len(a)
    len2 = len(b)

    if len1 > len2:
        b = "0" * (len1 - len2) + b
    else:
        a = "0" * (len2 - len1) + a
    
    return a, b

def bitwise_xor(string1, string2):
    str1, str2 = make_string_equal_length(string1, string2)
    result = ''
    for a_bit, b_bit in zip(str1, str2):
        if a_bit == b_bit:
            result += "0"
        else:
            result += "1"
    return result

print(bitwise_xor("1111","101010"))

The output of the above program is:

100101