Python Programming: An Introduction to Computer Science

(Nora) #1
4.6.EXERCISES 57

Forcompleteness,I shouldmentionthatstringsarealsoobjectsinPython.If youhave a relativelynew
versionofPython(2.0orlater),youcanusestringmethodsinplaceofthestringlibraryfunctionsthatwe
discussedearlier. Forexample,


myString.split()


is equivalentto


string.split(myString)


If thisobjectstuff soundsconfusingrightnow, don’t worry;Chapter5 is allaboutthepowerofobjects(and
prettypictures,too).


4.6 Exercises



  1. Giventheinitialstatements:


import string
s1 = "spam"
s2 = "ni!"

Show theresultofevaluatingeachofthefollowingstringexpressions.

(a)"The Knights who say," + s2
(b)3 * s1 + 2 * s2
(c)s1[1]
(d)s1[1:3]
(e)s1[2] + s2[:2]
(f)s1 + s2[-1]
(g)string.upper(s1)
(h)string.ljust(string.upper(s2),4) * 3


  1. Giventhesameinitialstatementsasinthepreviousproblem,showa Pythonexpressionthatcould
    constructeachofthefollowingresultsbyperformingstringoperationsons1ands2.


(a)"NI"
(b)"ni!spamni!"
(c)"Spam Ni! SpamNi! Spam Ni!"
(d)"span"
(e)["sp","m"]
(f)"spm"


  1. Show theoutputthatwouldbegeneratedbyeachofthefollowingprogramfragments.


(a)for ch in "aardvark":
print ch
(b)for w in string.split("Now is the winter of our discontent..."):
print w
(c)for w in string.split("Mississippi", "i"):
print w,
Free download pdf