[Tutor] Help needed

Wayne srilyk at gmail.com
Wed Jun 17 04:31:29 CEST 2009

On Tue, Jun 16, 2009 at 8:59 PM, ayyaz <ayyaz84 at gmail.com> wrote:

> The following works also.
> msg = raw_input("\nPlease enter a message to print backwards: ")
> x = range(0,len(msg))
> x.reverse()
> for i in x: print msg[i],

or even simpler, allow range to generate the reverse:

range(len(msg)-1, -1, -1)

Some explanation: len will actually give you a value that is out of range,
so you need len-1. So you'll start at the end, and go until you hit -1, and
your step is -1. If you did -2 at the end, you'll get every other letter in

And simpler still, just add that (or substitute xrange) to the loop:

for i in xrange(len(msg)-1, -1,-1): print msg[i]

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090616/a7331208/attachment.htm>

More information about the Tutor mailing list