Let's return to the note-passing example. Using the Python ord and chr functions, we can write some simple programs that automate the process of turning messages into strings of numbers and back again. The algorithm for encoding the message is simple.
get the message to encode for each character in the message:
print the letter number of the character
Getting the message from the user is easy, a raw_input will take care of that for us.
message = raw_input("Please enter the message to encode: ")
Implementing the loop requires a bit more effort. We need to do something for each character of the message. Recall that a for loop iterates over a sequence of objects. Since a string is a kind of sequence, we can just use a for loop to run-through all the characters of the message.
for ch in message:
Finally, we need to convert each character to a number. The simplest approach is to use the ASCII number (provided by ord) for each character in the message. Here is the final program for encoding the message:
# A program to convert a textual message into a sequence of
# numbers, utlilizing the underlying ASCII encoding.
print "This program converts a textual message into a sequence" print "of numbers representing the ASCII encoding of the message." print
# Get the message to encode message = raw_input("Please enter the message to encode: ") print print "Here are the ASCII codes:"
# Loop through the message and print out the ASCII values for ch in message:
print ord(ch), # use comma to print all on one line.
We can use the program to encode important messages.
This program converts a textual message into a sequence of numbers representing the ASCII encoding of the message.
Please enter the message to encode: What a Sourpuss!
Here are the ASCII codes:
87 104 97 116 32 97 32 83 111 117 114 112 117 115 115 33
One thing to notice about this result is that even the space character has a corresponding ASCII code. It is represented by the value 32.
Was this article helpful?