Reputation: 1242
Is it true that the last position of a string in python comes after the last character of that string?
If it is true does it mean if k='asdf'
then at index position 4 there is a ''
? If so, why doesn't k[4] return ''
instead of out of range error
.
It has been suggested to me to try k[4:4] to see this behavior but I think the slice returns a ''
because it hasn't been given anything to contain and not specifically because of presence of a ''
at the end of every string. If I do k[300:782], I still get ''
but `find('asdf','',300)' returns -1 so this should confirm my beliefs.
Upvotes: 2
Views: 1480
Reputation: 1828
Kyle does a great job of answering. I will only add that you can reference the last position of a string with the index -1. so in your example k[-1] produces 'f' just as k[3] produces 'f'.
Upvotes: 1
Reputation: 899
That is not true. The last position in k='asdf'
is k[3]
with is 'f'.
You are also correct that when trying to examine a slice that doesn't contain anything (k[4:4]
or k[300:2345]
or k[6:5]
) python will give you an empty result.
''
is an empty string; it is not returning a quotation mark.
@BrenBarn is absolutely right about find
Upvotes: 4