48 CHAPTER4. COMPUTINGWITHSTRINGS
import numbers2text
This program convertsa sequence of ASCII numbers into
the string of textthat it represents.
Please enter the ASCII-encodedmessage:
83 116 114 105 110 103115 32 97 114 101 32 70 117 110 33
The decoded messageis: Strings are Fun!
4.3.4 OtherStringOperations
Now wehave a coupleprogramsthatcanencodeanddecodemessagesassequencesofASCIIvalues.These
programsturnedouttobequitesimpleduetothepowerbothofPython’s stringdatatypeanditsbuilt-in
operationsaswellasextensionsthatcanbefoundinthestringlibrary.
Pythonis a verygoodlanguageforwritingprogramsthatmanipulatetextualdata.Table4.2listssome
oftheotherusefulfunctionsofthestringlibrary. Notethatmany ofthesefunctions,likesplit, accept
additionalparameterstocustomizetheiroperation.Pythonalsohasa numberofotherstandardlibrariesfor
text-processingthatarenotcoveredhere.Youcanconsulttheonlinedocumentationora Pythonreferenceto
findoutmore.
Function Meaning
capitalize(s) Copy ofswithonlythefirstcharactercapitalized
capwords(s) Copy ofswithfirstcharacterofeachwordcapitalized
center(s, width) Centersina fieldofgivenwidth
count(s, sub) Countthenumberofoccurrencesofsubins
find(s, sub) Findthefirstpositionwheresuboccursins
join(list) Concatenatelistofstringsintoonelargestring
ljust(s, width) Likecenter, butsis left-justified
lower(s) Copy ofsinalllowercasecharacters
lstrip(s) Copy ofswithleadingwhitespaceremoved
replace(s,oldsub,newsub) Replacealloccurrencesofoldsubinswithnewsub
rfind(s, sub) Likefind, butreturnstherightmostposition
rjust(s,width) Likecenter, butsis right-justified
rstrip(s) Copy ofswithtrailingwhitespaceremoved
split(s) Splitsintoa listofsubstrings(seetext).
upper(s) Copy ofswithallcharactersconvertedtouppercase
Table4.2:SomecomponentsofthePythonstringlibrary
4.3.5 FromEncodingtoEncryption
We have lookedat how computersrepresentstringsasa sortofencodingproblem.Eachcharacterina string
is representedbya numberthatis storedinthecomputerina binaryrepresentation.Youshouldrealizethat
thereis nothingreallysecretaboutthiscodeat all.Infact,wearesimplyusinganindustry-standardmapping
ofcharactersintonumbers.Anyonewitha littleknowledgeofcomputersciencewouldbeabletocrackour
codewithverylittleeffort.
Theprocessofencodinginformationforthepurposeofkeepingit secretortransmittingit privatelyis
calledencryption. Thestudyofencryptionmethodsis anincreasinglyimportantsubfieldofmathematicsand
computerscienceknownascryptography. Forexample,if youshopover theInternet,it is importantthatyour
personalinformationsuchassocialsecuritynumberorcreditcardnumberis transmittedusingencodingsthat
keepit safefrompotentialeavesdroppersonthenetwork.
Oursimpleencoding/decodingprogramsusea veryweakformof encryptionknownasasubstitution
cipher. Eachcharacteroftheoriginalmessage,calledtheplaintext, is replacedbya correspondingsymbol
(inourcasea number)fromacipheralphabet. Theresultingcodeis calledtheciphertext.