Length of new word outside of scope?


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<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.

```python

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
else:
print ‘empty’

<do not remove the three backticks above>

#2

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

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

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


#3

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.


#4

Because the stop index is exclusive.


#5

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

.A.B.C.D.E.F.

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.


#7

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


#8

A slice consists of…

list_or_string [ start_index : stop_index : step_value ]

exlcusive means not included.


#9

Thank you for the explanations.


#10

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


#11

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