#10. Ending Up. How does slicing work?


#1


https://www.codecademy.com/en/courses/python-beginner-2W5v7/1/5?curriculum_id=4f89dab3d788890003000096


My confusion is about the behavior of the slicing the string to make our pig latin translation. So with our entered word, why is it that we slice the string as follows:
new_word[1:len(new_word)]
instead of like so:
new_word[1:len(new_word)-1]

Take for example an 8 character string. Length of this string is 8. But since character positions in a string start at 0, our last character is at position 7. Why is it then that we are slicing our string to end at the length which is one greater than the position of the final character.


pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
    print original
else:
    print 'empty'
    
word = original.lower()
first = word[0]

new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
print new_word


#2

LIke range() the upper limit is excluded.

range(10)   # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]   (Python 2)

Note that there are still ten entries.

 > example = "The length is one more than the last index" 
.. 
   
 > len(example)
=> 42
 > example[42]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

 > example[:42]
=> 'The length is one more than the last index'
 > example[41:42]
=> 'x'
 >

#3

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