Python: How can i invert string "0110010"?


How to convert strings containing only 0s and 1s in most efficient and elegant way?

input:  "0110010"
output: "1001101"

Thanks in advance.

Asked By: Avo Asatryan



This piece of code works with strings, try it:

>>> from string import maketrans
>>> initial_string = "10101010100011010"
>>> converted_string = initial_string.translate(maketrans("10","01"))

>>> converted_string    # The result is
Answered By: J Johnson

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

#Or if you want to print out the binary, try

Here are some examples:

>>> ~0b110011
>>> bin(~0b110001)
>>> bin(~0b11000)

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.

Answered By: Jacob Garby

The simple way by use swapping:

st = "0110010"
print (st)
Answered By: Rohit-Pandey
''.join('1' if x == '0' else '0' for x in '0110010')
Answered By: RobertB
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.