Python Programming: An Introduction to Computer Science

(Nora) #1
4.4.OUTPUTASSTRINGMANIPULATION 49

Evenif ourcipherwerenotbasedonthewell-knownASCIIencoding,it wouldstillbeeasytodiscover
theoriginalmessage. Sinceeachletterisalwaysencodedbythesamesymbol,a code-breakercoulduse
statisticalinformationaboutthefrequency ofvariouslettersandsomesimpletrialanderrortestingto discover
theoriginalmessage.Suchsimpleencryptionmethodsmaybesufficientforgrade-schoolnotepassing,but
they arecertainlynotuptothetaskofsecuringcommunicationoverglobalnetworks.
Modernapproachestoencryptionstartbytranslatinga messageintonumbers,muchlike ourencoding
program.Thensophisticatedmathematicalalgorithmsareemployedtotransformthesenumbersintoother
numbers.Usually, thetransformationis basedoncombiningthemessagewithsomeotherspecialvaluecalled
thekey. Inordertodecryptthemessage,thepartyonthereceivingendneedstohave theappropriatekey so
thattheencodingcanbereversedtorecover theoriginalmessage.
Encryptionapproachescomeintwo flavors:privatekeyandpublickey.Ina privatekey systemthesame
key isusedforencryptinganddecryptingmessages. Allpartiesthatwishtocommunicateneedtoknow
thekey, butit mustbekeptsecretfromtheoutsideworld.Thisis usualsystemthatpeoplethinkofwhen
consideringsecretcodes.
Inpublickey systems,thereareseparatebutrelatedkeysforencryptinganddecrypting.Knowingthe
encryptionkey doesnotallowyoutodecryptmessagesordiscoverthedecryptionkey. Ina publickey
system,theencryptionkey canbemadepubliclyavailable,whilethedecryptionkey is keptprivate.Anyone
cansafelysenda messageusingthepublickey forencryption. Onlythepartyholdingthedecryptionkey
willbeabletodecipherit.Forexample,a securewebsitecansendyourwebbrowseritspublickey, andthe
browsercanuseit toencodeyourcreditcardinformationbeforesendingit ontheInternet. Thenonlythe
company thatis requestingtheinformationwillbeabletodecryptandreadit usingtheproperprivatekey.


4.4 OutputasStringManipulation


Evenprogramsthatwemaynotview asprimarilydoingtext-manipulationoftenneedtomake useofstring
operations.Forexample,a programtodoa financialanalysismustproducea nicelyformattedreportofthe
results.Muchofthisreportwillbeintheformoftextthatis usedtolabelandexplainnumbers,charts,tables
andfigures.Inthissection,we’ll lookat techniquesforgeneratingnicelyformattedtext-basedoutput.


4.4.1 ConvertingNumberstoStrings.


IntheASCIIdecodingprogram,weusedtheevalfunctiontoconvertfroma stringdatatypeintoa numeric
datatype.Recallthatevalevaluatesa stringasa Pythonexpression.It is verygeneralandcanbeusedto
turnstringsintonearlyany otherPythondatatype.
It is alsopossibletogotheotherdirectionandturnmany Pythondatatypesintostringsusingthestr
function.Herearea coupleofsimpleexamples.





str(500)
’500’
value = 3.14
str(value)
’3.14’
print "The valueis", str(value) + "."
The value is 3.14.





Noticeparticularlythelastexample.Byturningvalueintoa string,wecanusestringconcatenationtoput
a periodat theendofa sentence.If wedidn’t firstturnvalueintoa string,Pythonwouldinterpretthe+as
a numericaloperationandproduceanerror, because“.” is nota number.
Addingevalandstrto thetype-conversionoperationsdiscussedin Chapter3, wenow have a complete
setofoperationsforconvertingvaluesamongvariousPythondatatypes.Table4.3summarizesthesefive
Pythontypeconversionfunctions.
Onecommonreasonforconvertinga numberintoa stringissothatstringoperationscanbeusedto
controlthewaythevalueis printed. Forexample,inthefactorialprogramfromlastchapterwesawthat
Pythonlongintshave theletter“L” appendedtothem.InversionsofPythonpriorto2.0,the“L” showedup

Free download pdf