[Tutor] (no subject)
Brian van den Broek
bvande at po-box.mcgill.ca
Thu Apr 14 09:10:46 CEST 2005
Jim and Laura Ahl said unto the world upon 2005-04-14 02:09:
> How come when I ask it to print i[2:4] from an inputted string it
> gives me the letters between two and four
>
> But when I ask it to print i[-1:-4] it does not print anything.
>
> Jim
>
Hi Jim,
good to see you are still working at it. And posting some bits of code
to focus a response around is helpful :-)
>>> 'my test string'[-1:-4]
''
This tells Python to start at the end of the string and go *forward*,
one position at a time, up to, but not including, the -4 position.
But, since there is nothing forward from the end of the string, this
gives the empty string.
That suggests we need to one of two things:
>>> 'my test string'[-1:-4:-1]
'gni'
>>>
That says start at the end and go *backwards*, one position at a time,
up to, but not including, the -4 position.
Or,
>>> 'my test string'[-4:-1]
'rin'
>>>
This says start at the -4 position and go forwards, one position at a
time, up to, but not including the -1 position (i.e. the last letter).
We can also do
>>> 'my test string'[-4:]
'ring'
>>>
to remove the "but not including the -1 position" part of the instruction.
Try playing around with indexes using 1, 2, or 3, `slots'[*] and
specifying all, none, or some, and see what comes out. If you don't
understand the results, post again with the examples you don't understand.
[*] slots? I mean:
'I am indexed with 1 slot'[4]
'I am indexed with 2 slots'[4:6]
'I am indexed with 3 slots'[4:6:1]
'None of my slots have been "specified" '[:]
(There must be a better term that `slots', but it is 3am :-)
Best,
Brian vdB
More information about the Tutor
mailing list