On Tue, Feb 7, 2012 at 5:41 AM, Steven D'Aprano <st...@pearwood.info> wrote: > myles broomes wrote: >> >> Im trying to code a program where the user enters a message and it is >> returned backwards. Here is my code so far: >> message = input("Enter your message: ") >> backw = "" >> counter = len(message) >> while message != 0: >> backw += message[counter-1] >> counter -= 1 >> print(backw) >> input("\nPress enter to exit...") > > > When you want to do something with each item in a sequence, such as each > character in a string, you can do it directly: > > for char in message: > print(char) > > > prints the characters one at a time. > > Python has a built-in command to reverse strings. Actually, two ways: the > hard way, and the easy way. The hard way is to pull the string apart into > characters, reverse them, then assemble them back again into a string: > > > chars = reversed(message) # Gives the characters of message in reverse > order. > new_message = ''.join(chars) > > > Or written in one line: > > > new_message = ''.join(reversed(message)) > > > Not very hard at all, is it? And that's the hard way! Here's the easy way: > using string slicing. > > new_message = message[::-1] > > > I know that's not exactly readable, but slicing is a very powerful tool in > Python and once you learn it, you'll never go back. Slices take one, two or > three integer arguments. Experiment with these and see if you can understand > what slicing does and what the three numbers represent: > > > message = "NOBODY expects the Spanish Inquisition!" > > message[0] > message[1] > > message[39] > message[38] > > message[-1] > message[-2] > > message[0:6] > message[:6] > > message[19:38] > message[19:-1] > message [19:-2] > > message[::3] > message[:30:3] > message[5:30:3] > > > Hint: the two and three argument form of slices is similar to the two and > three argument form of the range() function. > > > Python gives you many rich and powerful tools, there's no need to mess about > with while loops and indexes into a string and nonsense like that if you > don't need to. As the old saying goes, why bark yourself if you have a dog? > > > > -- > Steven > > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor
While you should know about reverse, and understand slices, your program will work if you test for while counter != 0 instead of message. Message doesn't change message = input("Enter your message: ") backw = "" counter = len(message) #while message != 0: # not this while counter != 0: # this backw += message[counter-1] counter -= 1 print(backw) input("\nPress enter to exit...") -- Joel Goldstick _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor