[Tutor] Python 101 at devshed.com confusion

Glen Wheeler wheelege@tsn.cc
Thu, 28 Jun 2001 19:15:29 +1000


> Hey everyone,
>
> I'm just learning Python, and have been enjoying working through the
Python
> 101 articles on devshed.  I'm confused about something in part 2 of the
> Python 101 article, under the Sliced And Diced section...
>
> http://www.devshed.com/Server_Side/Python/Python101_2/page6.html
>
> At the beginning of the example, I'm told that the index of a string
begins
> with 0 at the first character.  Where I get confused is right away when I
> extract a substring...
>
> >>> str = "hobgoblin"
> >>> str[3:9]
> 'goblin'
> >>>
>
> When I walk through this in my Python interpreter, I get an error when I
try
> this...
>
> >>> str = "hobgoblin"
> >>> str[9]
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> IndexError: string index out of range
> >>>
>
> It makes perfect sense to me when using the len() function that I get a
> response that there are 9 characters in the string, but when I count
through,
> starting at 0 for the first character, I only come up with eight for the
last
> character too, just like the interpreter did.  So how come the first
example,
> indexing [3:9] works?

  Yup yup, well have a look at this little session...

>>> s = 'Jimbo McJim'
>>> s[1:3]
'im'            ## uh-huh, we knew that
>>> s[:10]
'Jimbo McJi'    ## yup, again expected
>>> s[10]
'm'             ## the 'cutting place' for slices is to the left of that
index
>>> s[:11]
'Jimbo McJim'   ## again, expected
>>> s[:12]
'Jimbo McJim'   ## hmmm seems it just truncates down to the available
characters...
>>> s[:155]
'Jimbo McJim'   ## how convenient!

  As you can see, the slice would of worked it is was str[3:124].  However,
when we want all of a list from a point, we can use str[3:] - sort of like
str[3:len(str)].
  Hope that helped,
  Glen.