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

Tim Chase python.list at tim.thechases.com
Tue Oct 7 15:07:03 EDT 2008


gcmartijn at gmail.com wrote:
> Why is this not working ?
> 
> bla = 'hondenriem'
> print bla[0:4]  # correct ! (= hond)
> print bla[3:2]  # nothing ! (= en)
> print bla[6:3]  # nothing ! (= riem)
> 
> Why don't bla[3:2] and bla[6:3] won't work ?
> 
> I use this version:
> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
> (Intel)] on win32
> 
> http://docs.python.org/tutorial/introduction.html#strings
> word = 'HelpA'
>>>> word[4]
> 'A'
>>>> word[0:2]
> 'He'
>>>> word[2:4]
> 'lp'

The 2nd number in a slice is the final position, not the number 
of characters:

 >>> bla = 'hondenriem'
 >>> print bla[0:4]
hond
 >>> print bla[3:2]  # returns nothing

 >>> print bla[3:3+2] # returns 2 characters from pos 3-5
de
 >>> print bla[6:6+3] # returns 3 characters from pos 6-9
rie


-tkc









More information about the Python-list mailing list