Old C coder, trying to verify details of python string indexing


#1

Here’s a sample of code:

s = girl
print len(s) # the length of s is 4, with valid indexes of 0 through 3
for i in range (0, len(s)):
print s[i]
++i

The output is:

4
g
i
r
l

My question is: if the length of “girl” is 4, and I’m printing out the letters from 0 to 4, but the only valid characters of the string are indexed from 0 through 3, why isn’t an error thrown for a range violation? I’ve played with outputting in the range 0:len(s)-1 and get the letters “gir”, so it’s not that python is indexing a nul character at the end of the string in the code snippet above.
Why, when python strings are indexed from zero, is the character at s[4] above the letter ‘l’? This can’t be true. What is true with regard to how this output is legal?
Thanks.


#2

Hi @wevets`

4 is the stop value of the range that you specified. Accordingly, the final value in that range would be 1 less than the stop value, so it is 3. Therefore, there is no indexing problem with it.

See the Python: range documentation.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.