42 CHAPTER4. COMPUTINGWITHSTRINGS
tosevenlettersoftheuser’s lastname. Usingthismethod,theusernameforElmerThudpuckerwouldbe
“ethudpuc,” andJohnSmithwouldjustbe“jsmith.”
We wanttowritea programthatreadsa person’s nameandcomputesthecorrespondingusername.Our
programwillfollow thebasicinput-process-outputpattern.Theresultis simpleenoughthatwecanskipthe
algorithmdevelopmentandjumprighttothecode.Theoutlineofthealgorithmis includedascommentsin
thefinalprogram.
username.py
Simple stringprocessing program to generate usernames.
def main():
print "This programgenerates computer usernames."
print
# get user’s firstand last names
first = raw_input("Pleaseenter your first name (all lowercase):")
last = raw_input("Pleaseenter your last name (all lowercase):")
# concatenate firstinitial with 7 chars of the last name.
uname = first[0]+ last[:7]
# output the username
print "Your usernameis:", uname
main()
Thisprogramfirstusesrawinputtogetstringsfromtheuser. Thenindexing,slicing,andconcatenation
arecombinedtoproducetheusername.
Here’s anexamplerun.
This program generatescomputer usernames.
Please enter your firstname (all lowercase): elmer
Please enter your lastname (all lowercase): thudpucker
Your username is: ethudpuc
Asyoucansee,computingwithstringsis verysimilartocomputingwithnumbers.
Hereis anotherproblemthatwecansolve withstringoperations.Supposewewanttoprinttheabbrevia-
tionofthemonththatcorrespondsto a givenmonthnumber. Theinputto theprogramis anintthatrepresents
a monthnumber(1–12),andtheoutputis theabbreviationforthecorrespondingmonth.Forexample,if the
inputis 3, thentheoutputshouldbeMar, forMarch.
Atfirst,it mightseemthatthisprogramis beyondyourcurrentability. Experiencedprogrammersrecog-
nizethatthisis a decisionproblem.Thatis,wehave todecidewhichof 12 differentoutputsis appropriate,
basedonthenumbergivenbytheuser. We willnotcoverdecisionstructuresuntillater;however, wecan
writetheprogramnow bysomecleveruseofstringslicing.
Thebasicideais tostoreallthemonthnamesina bigstring.
months = "JanFebMarAprMayJunJulAugSepOctNovDec"
We canlookupa particularmonthbyslicingouttheappropriatesubstring.Thetrickis computingwhereto
slice.Sinceeachmonthis representedbythreeletters,if weknew wherea givenmonthstartedinthestring,
wecouldeasilyextracttheabbreviation.
monthAbbrev = months[pos:pos+3]
Thiswouldgetusthesubstringoflengththreethatstartsinthepositionindicatedbypos.
How dowecomputethisposition?Let’s trya few examplesandseewhatwefind.Rememberthatstring
indexingstartsat 0.