1

I think this code should be break. positon of "c" in string "abc" is -1, so it should break, but why didn't?

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)

I think this code should be break. positon of "c" in string "abc" is -1, so it should break, but why didn't?

jpp
  • 159,742
  • 34
  • 281
  • 339
sky
  • 23
  • 3
  • string = "cabc" print(string[-1]) while True: position = string.find("c") if position == -1: break string = string[:position] + "f" + string[position+len("c"):] print(string) – sky Jan 25 '19 at 12:02

2 Answers2

3

The indexing syntax mystr[-1] gives you the last element of mystr, but that is a convenience of the indexing syntax. When you use find() you get a number counting from zero, so 2 in this case. The return value -1 means not found.

You are overgeneralizing the -1 convention: it doesn't apply to find. If it did, then string.find("c") could equally well return -1 or 2 in this example because both would be correct. That would be inconvenient, to say the least.

BoarGules
  • 16,440
  • 2
  • 27
  • 44
  • 1
    The `-1` is not a "convention" that gives the last element, it just is a python tool that means : If I request a negative index, begin from the end of string instead of the beginning. – IMCoins Jan 25 '19 at 12:10
  • When you decide that negative indexes count from the end of the string, that *is* a convention. Without that convention, negative indexes would always be out of range, as they are in many other languages. It is a different way of interpreting what negative numbers mean. – BoarGules Jan 25 '19 at 12:14
  • I think I can agree with you on this point. Where I disagree though is that your answer could make him think that the -1 index is just a way to request to last item, when there is a whole more complicated system behind. But that may be just me that is complicating things – IMCoins Jan 25 '19 at 12:17
1

str.find gives a positive integer index, so position = 2 in your example.

The preferred solution is to simply test against the length of your string:

if position == len(string) - 1:
    # do something

Alternatively, for the negative index, you can redefine position:

position = string.find('c') - len(string)  # -1

However, be careful: if your character is not found, str.find returns -1. So there is good reason why positive integers are preferred in the first place.

See this answer for a diagram of how negative indexing works.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • You may explain how negative indexes works, since it was his original question I believe. "positon of "c" in string "abc" is -1", he said. – IMCoins Jan 25 '19 at 12:08
  • @IMCoins, Yup I've added a link for that with a useful diagram :) – jpp Jan 25 '19 at 12:10