Python Programming: An Introduction to Computer Science

(Nora) #1
4.3.STRINGSANDSECRETCODES 47




eval("345.67")
345.67
eval("3+4")
7
x = 3.5
y = 4.7
eval("x * y")
16.45
x = eval(raw_input("Enter a number "))
Enter a number 3.14
print x
3.14





Thelastpairofstatementsshowsthattheevalofarawinputproducesexactlywhatwewouldexpect
fromaninputexpression.Remember,inputevaluateswhattheusertypes,andevalevaluateswhatever
stringit is given.
Usingsplitandevalwecanwriteourdecoderprogram.


numbers2text.py


A program to converta sequence of ASCII numbers into


a string of text.


import string # includestring library for the split function.


def main():
print "This programconverts a sequence of ASCII numbers into"
print "the stringof text that it represents."
print


# Get the messageto encode
inString = raw_input("Please enter the ASCII-encoded message:")

# Loop througheach substring and build ASCII message
message = ""
for numStr in string.split(inString):
asciiNum = eval(numStr) # convert digit stringto a number
message = message+ chr(asciiNum) # append character to message

print "The decodedmessage is:", message

main()


Studythisprograma bit,andyoushouldbeabletounderstandexactlyhow it accomplishesitstask.The
heartoftheprogramis theloop.


for numStr in string.split(inString):
asciiNum = eval(numStr)
message = message+ chr(asciiNum)


Thesplitfunctionproducesa sequenceofstrings,andnumStrtakesoneachsuccessive (sub)stringinthe
sequence.I calledtheloopvariablenumStrtoemphasizethatitsvalueis a stringofdigitsthatrepresents
somenumber. Eachtimethroughtheloop,thenextsubstringisconvertedtoa numberbyevalingit.
ThisnumberisconvertedtothecorrespondingASCIIcharacterviachrandappendedtotheendofthe
accumulator,message. Whentheloopis finished,everynumberininStringhasbeenprocessedand
messagecontainsthedecodedtext.
Hereis anexampleoftheprograminaction:

Free download pdf