print command don't work (subscripted) word[2:4]

Jerry Hill malaclypse2 at gmail.com
Tue Oct 7 21:20:24 CEST 2008


On Tue, Oct 7, 2008 at 2:50 PM,  <gcmartijn at gmail.com> wrote:
> Why is this not working ?
>
> bla = 'hondenriem'
> print bla[0:4]  # correct ! (= hond)
> print bla[3:2]  # nothing ! (= en)

Why do you think the right answer is 'en'?  bla[3:2] is asking for the
slice starting at position 3, ending before position 2, reading left
to right.  If you were expecting the slice to read backwards from
position 3 to position 2, you'd need to supply a third argument to the
slice:

>>> print bla[3:2:-1]
d

If you were expecting the second argument in the slice notation to be
the length of the substring, well, that's just wrong.  Python slices
don't work that way.  Take a look at the tutorial, particularly the
bit on slice notation, here:
http://docs.python.org/tutorial/introduction.html#strings

-- 
Jerry



More information about the Python-list mailing list