3

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
0

3 Answers 3

0
def flip(binary_str):    
    return ''.join('0' if i == '1' else '1' for i in binary_str)
Sign up to request clarification or add additional context in comments.

1 Comment

Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes.
0

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'

Comments

0

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"))

1 Comment

a verbal explanation is often helpful