Christian Wyglendowski wrote: >Liam said: > > >>How about - >>print "\n\nWelcome to the Backwards Message Display." >>print >>message = raw_input("\nPlease Enter a Message.") >>msgAsList = [ char for char in message] >> >> > >You could also do: > >msgAsList = list(message) > >list() takes any iterable and returns a list object. > > > >>msgAsList.reverse() >>reversedMessage = ''.join(msgAsList) >> >> > >In Python 2.4, the following is also possible: > >reversedMessage = ''.join(reversed(list(message))) > >It's amazing how in Python even one-liners can be so pretty :-) > >Christian >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > Or you could just do the following:
>>> print "\n\nWelcome to the Backwards Message Display." >>> print >>> message = raw_input("\nPlease Enter a Message.") >>> print message[::-1] This is the equivalent of print ''.join(reversed(message)), since reversed works on any iterable sequence, including strings. In any case, the syntax for this sort of thing in general is: sequence[start:stop:step], with start defaulting to 0, step defaulting to sys.maxint (which, for all intents and purposes, means the end of the string), and step defaulting to 1. However, when step is negative, start and end switch defaults. So by doing [::-1], you're telling Python to return the values of the sequence that can be found from the end to the start Another way to do this would be: >>> import sys >>> for i in range(len(sequence)-1,-1,-1): sys.stdout.write(sequence[i]) # to remove spaces between elements, # which would be produced by the more # intuitive "print sequence[i]," technique So, the first time around, i is len(sequence)-1, or the last element, because that's the start value. Next, it's len(sequence)-2, or the second to last element, because the step is -1. etc . . . Until the last round when i is 0, after which step is added to i and i==-1, so the loop is not re-entered. HTH, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor