Using bitwise operators:
s = '1001011101010010101010100100000001111011010101'
i = int(s,2)
i=((1<<i.bit_length())-1)^i
t=bin(i)[2:].zfill(len(s))
print(s)
print(t)
Output:
1001011101010010101010100100000001111011010101
0110100010101101010101011011111110000100101010
Explanation:
First I convert the string to an integer (s -> i
).
Then I make a number that has the same length as i
in binary but has all ones.
This is achieved by bitshifting 1
to the left n
times where n
is the length of the binary string, it's safer to use the .bit_length()
method of the integer though.
This bitshifted integer is still the power of two so we have to subtract 1 to get all ones.
Then using the xor (exclusive or) operator the result will be the opposite of the input's.
After this it's just changing back to binary string, removing the 0b
part from the start and filling with zeroes to the left to match the length of the original string.