40 CHAPTER4. COMPUTINGWITHSTRINGS
firstName = input("Pleaseenter your name: ")
Please enter your name:"John"
print "Hello",firstName
Hello John
Thisworks,butit is nota verysatisfactorysolution.We shouldn’t have toburdentheusersofourprograms
withdetailslike typingquotesaroundtheirnames.
Pythonprovidesa bettermechanism.Therawinputfunctionis exactlylikeinputexceptit doesnot
evaluatetheexpressionthattheusertypes.Theinputis simplyhandedtotheprogramasa stringoftext.
Revisitingourexample,hereis how it lookswithrawinput:
firstName = raw_input("Pleaseenter your name: ")
Please enter your name:John
print "Hello",firstName
Hello John
Noticethatthisexampleworksasexpectedwithouthavingtotypequotesaroundtheinput.If youwantto
gettextualinputfromtheuser,rawinputis thewaytodoit.
Sofar, wehave seenhowtogetstringsasinput,assignthemtovariablesandprintthemout. That’s
enoughtowritea parrotprogram,butnottodoany serioustext-basedcomputing.Forthat,weneedsome
stringoperations.Therestofthissectiontakesyouona tourofthemoreimportantPythonstringoperations.
Inthefollowingsection,we’ll puttheseideastoworkinsomeexampleprograms.
Whiletheideaofnumericoperationsmaybeoldhattoyoufromyourmathstudies,youmaynothave
thoughtaboutstringoperationsbefore.Whatkindsofthingscanwedowithstrings?
Forstarters,rememberwhata stringis: a sequenceofcharacters. Onethingwemightwanttodois
accesstheindividualcharactersthatmake upthestring.InPython,thiscanbedonethroughtheoperationof
indexing. We canthinkofthepositionsin a stringasbeingnumbered,startingfromtheleftwith0.Figure4.1
H e l l o B o b
0 1 2 3 4 5 6 7 8
Figure4.1:Indexingofthestring”HelloBob”
illustrateswiththestring“HelloBob.” Indexingis usedinstringexpressionstoaccessa specificcharacter
positioninthestring.Thegeneralformforindexingis
determineswhichcharacteris selectedfromthestring.
Herearesomeinteractive indexingexamples:
greet = "HelloBob"
greet[0]
’H’
print greet[0],greet[2], greet[4]
H l o
x = 8
print greet[x-2]
B
Noticethat,ina stringofncharacters,thelastcharacteris at positionn 1, becausetheindexesstartat 0.
Indexingreturnsa stringcontaininga singlecharacterfroma largerstring.It is alsopossibletoaccess
a contiguoussequenceofcharactersorsubstringfroma string.InPython,thisis accomplishedthroughan
operationcalled slicing. Youcanthinkofslicingasa wayofindexinga rangeofpositionsinthestring.
Slicingtakestheform string [ start : end ]. Bothstartandendshouldbeint-valued
expressions.Asliceproducesthesubstringstartingatthepositiongivenbystartandrunningupto,but
notincluding, positionend.
Continuingwithourinteractive example,herearesomeslices.