[Tutor] Tutor Digest, Vol 21, Issue 79

Chris or Leslie Smith smiles at worksmail.net
Fri Nov 18 16:19:48 CET 2005


Orri Ganel wrote:

Another way to do this would be:
| 
|||| import sys
|||| for i in range(len(sequence)-1,-1,-1):
|       sys.stdout.write(sequence[i]) 
|| 

It might be interesting to note that although this *range* works for accessing the indices, you can't do the same directly in slice notation:

######
>>> 'abc'[2:-1:-1]
''
>>> 'abc'[2:0:-1]
'cb'
>>> 'abc'[::-1]
'cba'
######

In the first case the -1 refers to the same position in the string as the 2 so this is a null slice. And in the second case, we miss the first character because the indices only go up *to* the zero (thus through 1) and not through 0.  Fortunately, we can let Python handle the problem by just leaving off the indices as has already been pointed out and is shown in the 3rd example.

/c




More information about the Tutor mailing list