Skip to content
Advertisement

Flipping a binary in a string

I am new to python and coding in general. So what I am trying to achieve is to flip each bit in a binary string (for eg. if I input ‘110’ the output should be ‘001’). I specifically need to use the while loop and I need to define it as a function. Here is what I’ve tried so far:

def flip(binary_string):
    new_string= ''
    i=0
    while i<len(binary_string):
        if i == '0':
            new_string=new_string+ '1'
        if i == '1':
            new_string= new_string+ '0'
        i=i+1    
    return new_string

however it just returns the empty new_string as defined in the beginning. What’s wrong with my code? any help would be greatly appreciated

Advertisement

Answer

You were comparing the array index and not the element. Fixed that in the code below.

def flip(binary_string):
    new_string= ''
    i=0
    while i<len(binary_string):
        if binary_string[i] == '0':
            new_string=new_string+ '1'
        if binary_string[i] == '1':
            new_string= new_string+ '0'
        i=i+1    
    return new_string


flip("100")
>>> 011
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement