why this code didn't break? | Sololearn: Learn to code for FREE!

why this code didn't break?

string = "abc" print(string[-1]) while True: position = string.find("c") if position == -1: break string = string[:position] + "f" + string[position+len("c"):] print(string) c in string is the latest one the position is -1, so i think it should go break.

25th Jan 2019, 12:27 PM
1 Answer
+ 5
-1 works for list indices, not characters in strings (at least not in this case). -1 will be returned on failure (character not found), not if the character you're looking for is the last character of the string. You should use something like "if position == len(string)-1" or "if string.endswith('c')" instead. And never use "string", "list" etc. as a name for a string, list etc. It's not necessarily wrong, but bad style and can possibly break your code.
25th Jan 2019, 12:34 PM
Anna - avatar