Length of new word outside of scope?



<Below this line, add a link to the EXACT exercise that you are stuck at.>
I’m stuck on the exercise to print the the new word from the second character to the last.

<In what way does your code behave incorrectly? Include ALL error messages.>
I don’t think it should be from new_word[1:len(new_word)].

<What do you expect to happen instead?>
I think it should be from new_word[1:len(new_word)-1] instead because the last character in the word has an index of len(new_word)-1. Without the -1 it would be outside of scope.


pyg = ‘ay’

original = raw_input(‘Enter a word:’)

if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)-1]
print original
print ‘empty’

<do not remove the three backticks above>


And you would be wrong. That is a valid statement.

>>> word = "thisisaword"
>>> word[1:len(word)]
>>> word[1:len(word)-1]

The moral of the story? Test your ideas before you begin to criticize.


And you would be wrong to think I didn’t test it.

Moral of the story? Don’t assume before you criticize.

My question is why it works that way.


Because the stop index is exclusive.


A way that helps me think of indexing, in regards to slicing;


The first dot represents the zero index, the second dot 1. The last dot represents len(word), and the penultimate dot is len(word) - 1, so it excludes F.

I’m only a beginner so I may not be explaining my thinking in the best way.


Would you mind explaining ‘stop index is exclusive’ to me?


A slice consists of…

list_or_string [ start_index : stop_index : step_value ]

exlcusive means not included.


Thank you for the explanations.


Thank you for asking this question, since I had it too. Seems there is much more to this than is explained in simple introduction.


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