You can just swap the two values instead of iterating over the string.
line='100000040000001' pos = line.index('4') ## move to the left line_as_list=list(line) if pos > 0: new_pos=pos - 1 ## move to right= pos + 1 save_this=line_as_list[new_pos] line_as_list[new_pos]='4' line_as_list[pos]=save_this ## print one above the other for easy comparison print(line) print("".join(line_as_list))