Python Programming: An Introduction to Computer Science

(Nora) #1
46 CHAPTER4. COMPUTINGWITHSTRINGS

add the characterto the end of message
print the message


Beforetheloop,theaccumulatorvariablemessageisinitializedtobeanemptystring, thatisa string
thatcontainsnocharacters("").Eachtimethroughtheloopa numberfromtheinputis convertedintoan
appropriatecharacterandappendedtotheendofthemessageconstructedsofar.
Thealgorithmseemssimpleenough,buteventhefirststeppresentsuswitha problem.How exactlydo
wegetthesequenceofnumberstodecode?We don’t evenknow how many numberstherewillbe.To solve
thisproblem,wearegoingtorelyonsomemorestringmanipulationoperations.
First,wewillreadtheentiresequenceofnumbersasa singlestringusingrawinput. Thenwewill
splitthebigstringintoa sequenceofsmallerstrings,eachofwhichrepresentsoneofthenumbers.Finally,
wecaniteratethroughthelistofsmallerstrings,converteachintoa number, andusethatnumbertoproduce
thecorrespondingASCIIcharacter. Hereis thecompletealgorithm:


get the sequence of numbersas a string, inString
split inString intoa sequence of smaller strings
message = ""
for each of the smallerstrings:
change the stringof digits into the number it represents
append the ASCIIcharacter for that number to message
print message


Thislookscomplicated,butPythonprovidessomefunctionsthatdojustwhatweneed.
We saw inChapter3 thatPythonprovidesa standardmathlibrarycontainingusefulfunctionsforcom-
putingwithnumbers. Similarly, thestringlibrarycontainsmany functionsthatareusefulinstring-
manipulationprograms.
Forourdecoder, wewillmake useofthesplitfunction.Thisfunctionis usedtosplita stringintoa
sequenceofsubstrings.Bydefault,it willsplitthestringwherever a spaceoccurs.Here’s anexample:





import string
string.split("Hello string library!")
[’Hello’, ’string’,’library!’]





Youcanseehowsplithasturnedtheoriginalstring"Hellostring library!"intoa listofthree
strings:"Hello","string"and"library!".
Bytheway, thesplitfunctioncanbeusedtosplita stringatplacesotherthanspacesbysupplying
thecharactertosplitonasa secondparameter. Forexample,if wehave a stringofnumbersseparatedby
commas,wecouldsplitonthecommas.





string.split("32,24,25,57", ",")
[’32’, ’24’, ’25’,’57’]





Sinceourdecoderprogramshouldacceptthesameformatthatwasproducedbytheencoderprogram,
namelya sequenceofnumberswithspacesbetween,thedefaultversionofsplitworksnicely.





string.split("87104 97 116 32 97 32 83 111 117 114 112 117 115 11533")
[’87’, ’104’, ’97’,’116’, ’32’, ’97’, ’32’, ’83’, ’111’, ’117’,
’114’, ’112’, ’117’,’115’, ’115’, ’33’]





Noticethattheresultinglistis nota sequenceofnumbers,it is a sequenceofstrings.It justsohappensthese
stringscontainonlydigitsandcouldbeinterpretedasnumbers.
Allthatweneednow is a wayofconvertinga stringcontainingdigitsintoa Pythonnumber. Onewayto
accomplishthisis withthePythonevalfunction.Thisfunctiontakesany stringandevaluatesit asif it were
a Pythonexpression.Herearesomeinteractive examplesofeval:





numStr = "500"
eval(numStr)
500




Free download pdf