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

G

gcmartijn

T

Tim Chase

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
 
S

skip

gcmartijn> Why is this not working ?
gcmartijn> bla = 'hondenriem'
gcmartijn> print bla[0:4] # correct ! (= hond)
gcmartijn> print bla[3:2] # nothing ! (= en)
gcmartijn> print bla[6:3] # nothing ! (= riem)

gcmartijn> Why don't bla[3:2] and bla[6:3] won't work ?

Because those two examples define zero-length slices (left index <= right).
The second number in each slice specification is the ending index of the
slice, not the desired length.
>>> bla = 'hondenriem'
>>> print bla[0:4] hond
>>> print bla[3:2]
>>> print bla[2:3] n
>>> print bla[6:3]
>>> print bla[3:6] den
>>> print bla[3:3]


Skip
 
J

Jerry Hill

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top