Flipping binary string python3

Viewed 528

How can I flip binary strings in python3?

If I have 001011, it should output 110100.

I want to define it def flip(binary_string)

here is what I've tried:

def flip(binary_string):
  for bit in binary_string:
    if bit == "1":
      "1" == "0"
    else:
      "0" == 1
    return binary_string
3 Answers

This code checks every character in the string and converts the 0s to 1s and vice versa:

def flip(binary_string):
    value = ""
    for bit in binary_string: value.join("1" if bit == "0" else "0")
    return value

print(flip("10110"))

You could make the characters into integers and then into strings again like this:

string = "0001010011110"

def flip(bstring):
    return "".join(str((int(c)+1)%2) for c in bstring)

flip(string)  # '1110101100001'
def flip(binary_str):    
    return ''.join('0' if i == '1' else '1' for i in binary_str)
Related