Just flip the values
if ( str [ k ] == '1' ) : NEW_LINE INDENT str = list ( str ) NEW_LINE str [ k ] = '0' NEW_LINE str = ' ' . join ( str ) NEW_LINE DEDENT else : NEW_LINE INDENT str = list ( str ) NEW_LINE str [ k ] = '1' NEW_LINE str = ' ' . join ( str ) NEW_LINE DEDENT k -= 1 NEW_LINE