[Tutor] (no subject)

Jim and Laura Ahl jcahl at psci.net
Thu Apr 14 18:08:22 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]
When I do this it tells me that the sequence index must be an integer.  What is that telling me and how do I fix that? Jim

That says start at the end and go *backwards*, one position at a time, 
up to, but not including, the -4 position.


 >>> 'my test string'[-4:-1]

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:]
Ok, I agree with what this is doing.  So if I type in  print i[-1] this gives me that last letter of the string. But when I type in  print i[-1:] it does nothing, because there is nothing after -1.  So I need to find some charecter that takes the string in the opposite direction.  like  print i[-1:-4]  but that does not print anything (why)?  When I put another number behind this it gives me it must be an integer    print  i[-1:-4:-1]  so what have I got messed up and why can't this work?  And if an iputted word or string in typed in how do you tell it to go to the end of it and stop?  I assumed that  print i[-1:]  would have done it

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


Brian vdB

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050414/44f9c000/attachment.htm

More information about the Tutor mailing list