Python Programming: An Introduction to Computer Science

(Nora) #1
50 CHAPTER4. COMPUTINGWITHSTRINGS

Function Meaning
float(<expr>) Convertexprtoa floatingpointvalue.
int(<expr>) Convertexprtoanintegervalue.
long(<expr> Convertexprtoa longintegervalue.
str(<expr>) Returna stringrepresentationofexpr.
eval(<string>) Evaluatestringasanexpression.

Table4.3:TypeConversionFunctions

whenever a longintwasprinted.However, it is easytoremove thisartifactusingsomestraightforwardstring
manipulation.


factStr = str(fact)
print factStr[0:len(factStr)-1]

Canyouseehowthiscodeturnsthelongintintoa stringandthenusesslicingtoremove the“L?”The
printstatementprintseverypositionin thestringupto,but notincluding,thefinal“L,” whichis in position
length - 1.
Asanaside,Pythonalsoallowssequencestobeindexedfromthebackbyusingnegative numbersas
indexes.Thus-1is thelastpositionina string,-2is thesecondtolast,etc.Usingthisconvention,wecan
sliceoff thelastcharacterwithoutfirstcomputingthelengthofthestring.


print str(fact)[:-1]

Thisversionusesstrto turnfactintoa stringandthenimmediatelyslicesit “inplace”fromthebeginning
(0is thedefaultstart)upto,butnotincluding,thelastposition.


4.4.2 StringFormatting.


Asyouhave seen,basicstringoperationscanbeusedtobuildnicelyformattedoutput. Thistechniqueis
usefulforsimpleformatting,butbuildingupa complex outputthroughslicingandconcatenationofsmaller
stringscanbetedious.Pythonprovidesa powerfulstringformattingoperationthatmakesthejobmucheasier.
Let’s startwitha simpleexample.Hereis a runofthechangecountingprogramfromlastchapter.


Change Counter


Please enter the countof each coin type.
How many quarters do you have? 6
How many dimes do you have? 0
How many nickels do youhave? 0
How many pennies do youhave? 0
The total value of yourchange is 1.5


Noticethatthefinalvalueis givenasa fractionwithonlyonedecimalplace.Thislooksfunny, sincewe
expecttheoutputtobesomethinglike$1.50.
We canfixthisproblembychangingtheverylastlineoftheprogramasfollows.


print "The total valueof your change is $%0.2f" % (total)


Now theprogramprintsthismessage:


The total value of yourchange is $1.50


Let’s tryto make somesenseofthis.Thepercentsign%is Python’s stringformattingoperator. Ingeneral,
thestringformattingoperatoris usedlike this:


% ()
Free download pdf