Chapter 4
Computing with Strings
Sofar, wehave beendiscussingprogramsdesignedtomanipulatenumbers.Thesedaysweknow thatcom-
putersarealsousefulforworkingwithotherkindsofdata.Infact,themostcommonuseformostpersonal
computersis wordprocessing.Thedatainthiscaseis text.Text is representedinprogramsbythestringdata
type,whichis thesubjectofthischapter.
4.1 TheStringDataType.
A stringis a sequenceofcharacters.InChapter2 youlearnedthata stringliteralis a sequenceofcharactersin
quotations.Pythonalsoallowsstringsto bedelimitedbysinglequotes(apostrophes).There’s nodifference—
justbesuretousea matchingset. Stringscanbestoredinvariables,justlike numbers.Herearesome
examplesillustratingthesetwo formsofstringliterals.
str1 = "Hello"
str2 = ’spam’
print str1, str2
Hello spam
type(str1)
<type ’string’>
type(str2)
<type ’string’>
Youalreadyknow how toprintstrings.Someprogramsalsoneedtogetstringinputfromtheuser(e.g.,
a name). Gettingstring-valuedinputrequiresa bitofcare. Rememberthattheinputstatementtreats
whatevertheusertypesasanexpressiontobeevaluated.Considerthefollowinginteraction.
firstName = input("Pleaseenter your name: ")
Please enter your name:John
Traceback (innermostlast):
File "<pyshell#8>",line 1, in?
firstName = input("Pleaseenter your name: ")
File "",line 0, in?
NameError: John
Somethinghasgonewronghere.Canyouseewhattheproblemis?
Remember, aninputstatementis justa delayedexpression.WhenI enteredthename,“John”,thishad
theexactsameeffectasexecutingthisassignmentstatement:
firstName = John
Thisstatementsays,“lookupthevalueofthevariableJohnandstorethatvalueinfirstName.” Since
Johnwasnever givena value,Pythoncannotfindany variablewiththatnameandrespondswithaNameError.
Onewaytofixthisproblemis totypequotesarounda stringinputsothatit evaluatesasa stringliteral.