Python: How can i invert string “0110010”? [closed]

I need to invert a string which contains only ‘0’s and ‘1’s(ex. input:”0110010″, output: “1001101”). Which is the best solution in terms of performance?

Answer

How to do this with either strings or binary literals.

Easy, use a bitwise operator. This is the proper way to do it, because it’s useful to understand how to use these operators in Python. If this is a task, this seems like the way whoever set the task wanted it to be done.

# Make binary literal (0b prefix)
b = 0b11001001
# And use the complement operator
print(~b)

#Or if you want to print out the binary, try
print(bin(~b))

Here are some examples:

>>> ~0b110011
-52
>>> bin(~0b110001)
'-0b110010'
>>> bin(~0b11000)
'-0b11001'

If your binary number is a string:

s = "101"
# bin(~int(s,2)) = "010"

Note, you might want to trim the first three characters off of the space if you want just the binary characters, e.g.

bin(~int(s,2))[3:]

Leave a Reply

Your email address will not be published. Required fields are marked *