Python Programming: An Introduction to Computer Science

(Nora) #1
4.2.SIMPLESTRINGPROCESSING 41




greet[0:3]
’Hel’
greet[5:9]
’ Bob’
greet[:5]
’Hello’
greet[5:]
’ Bob’
greet[:]
’Hello Bob’





Thelastthreeexamplesshowthatif eitherexpressionismissing,thestartandendofthestringarethe
assumeddefaults.Thefinalexpressionactuallyhandsbacktheentirestring.
Indexingandslicingareusefuloperationsforchoppingstringsintosmallerpieces.Thestringdatatype
alsosupportsoperationsforputtingstringstogether. Two handyoperatorsareconcatenation(+) andrepetition
(*).Concatenationbuildsa stringby“gluing”two stringstogether. Repetitionbuildsa stringbymultiple
concatenationsofa stringwithitself.Anotheruseful functionislen, whichtellshow many charactersare
ina string.Herearesomeexamples:





"spam" + "eggs"
’spameggs’
"Spam" + "And"+ "Eggs"
’SpamAndEggs’
3 "spam"
’spamspamspam’
"spam"
5
’spamspamspamspamspam’
(3 "spam") + ("eggs" 5)
’spamspamspameggseggseggseggseggs’
len("spam")
4
len("SpamAndEggs")
11





ThesebasicstringoperationsaresummarizedinTable4.1.


Operator Meaning
+ Concatenation
* Repetition
string [ ] Indexing
len( string ) length
string [ : ] slicing

Table4.1:Pythonstringoperations

4.2 SimpleStringProcessing


Nowthatyouhave anideawhatstringoperationscando,we’rereadytowritesomeprograms. Ourfirst
exampleis a programtocomputetheusernamesfora computersystem.
Many computersystemsusea usernameandpasswordcombinationtoauthenticatesystemusers.The
systemadministratormustassigna uniqueusernametoeachuser. Often,usernamesarederivedfromthe
user’s actualname. Oneschemeforgeneratingusernamesistousetheuser’s firstinitialfollowedbyup

Free download pdf