[Tutor] Backwards message program
Steven D'Aprano
steve at pearwood.info
Tue Feb 7 11:41:52 CET 2012
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
More information about the Tutor
mailing list