12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

8.4. String slices 73Thefollowingexampleshowshowtouseconcatenation(stringaddition)andaforlooptogeneratean abecedarian series (that is, in alphabetical order). In Robert McCloskey’s book Make Way forDucklings,thenamesoftheducklingsareJack,Kack,Lack,Mack,Nack,Ouack,Pack,andQuack.This loop outputs these names inorder:prefixes = 'JKLMNOPQ'suffix = 'ack'for letter in prefixes:print letter + suffixThe output is:JackKackLackMackNackOackPackQackOf course, that’s not quite rightbecause “Ouack” and “Quack” aremisspelled.Exercise 8.2 Modify theprogram tofix thiserror.8.4 StringslicesA segment ofastringiscalled aslice. Selecting asliceissimilartoselecting acharacter:>>> s = 'Monty <strong>Python</strong>'>>> print s[0:5]Monty>>> print s[6:12]<strong>Python</strong>Theoperator[n:m]returnsthepartofthestringfromthe“n-eth”charactertothe“m-eth”character,including the first but excluding the last. This behavior is counterintuitive, but it might help toimagine the indices pointing between thecharacters, as inthe followingdiagram:fruit’ b a n a n a ’index0 1 2 3 4 5 6If you omit the first index (before the colon), the slice starts at the beginning of the string. If youomit thesecond index, theslicegoes tothe end of thestring:>>> fruit = 'banana'>>> fruit[:3]'ban'>>> fruit[3:]'ana'

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!