Vous êtes sur la page 1sur 12

5/3/2014

Strings

Buy this book at Amazon.com

Chapter 8 Strings
8.1 A string is a sequence
A string is a sequence of characters. You can access the characters one at a time with the bracket operator:
> > >f r u i t=' b a n a n a ' > > >l e t t e r=f r u i t [ 1 ]

Are you using one of our books in a class? We'd like to know about it. Please consider filling out this short survey.

The second statement selects character number 1 from f r u i tand assigns it to l e t t e r . The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name). But you might not get what you expect:
> > >p r i n tl e t t e r a
Think Python Allen B. Downey

Privacy Information

For most people, the first letter of ' b a n a n a 'is b , not a . But for computer scientists, the index is an offset from the beginning of the string, and the offset of the first letter is zero.
> > >l e t t e r=f r u i t [ 0 ] > > >p r i n tl e t t e r b

So bis the 0th letter (zero-eth) of ' b a n a n a ' , ais the 1th letter (one-eth), and nis the 2th (two-eth) letter. You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. Otherwise you get:
> > >l e t t e r=f r u i t [ 1 . 5 ] T y p e E r r o r :s t r i n gi n d i c e sm u s tb ei n t e g e r s

Think Stats Allen B. Downey

Privacy Information

8.2 l e n
l e nis a built-in function that returns the number of characters in a string:
http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89 1/12

5/3/2014

Strings

> > >f r u i t=' b a n a n a ' > > >l e n ( f r u i t ) 6

To get the last letter of a string, you might be tempted to try something like this:
> > >l e n g t h=l e n ( f r u i t ) > > >l a s t=f r u i t [ l e n g t h ] I n d e x E r r o r :s t r i n gi n d e xo u to fr a n g e

Think Complexity Allen B. Downey

The reason for the I n d e x E r r o ris that there is no letter in b a n a n a with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from l e n g t h :
> > >l a s t=f r u i t [ l e n g t h 1 ] > > >p r i n tl a s t a
Privacy Information

Alternatively, you can use negative indices, which count backward from the end of the string. The expression f r u i t [ 1 ]yields the last letter, f r u i t [ 2 ] yields the second to last, and so on.

8.3 Traversal with a f o rloop


A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. One way to write a traversal is with a w h i l eloop:
i n d e x=0 w h i l ei n d e x<l e n ( f r u i t ) : l e t t e r=f r u i t [ i n d e x ] p r i n tl e t t e r i n d e x=i n d e x+1

Python for Software Design Allen B. Downey

Privacy Information

This loop traverses the string and displays each letter on a line by itself. The loop condition is i n d e x<l e n ( f r u i t ) , so when i n d e xis equal to the length of the string, the condition is false, and the body of the loop is not executed. The last character accessed is the one with the index l e n ( f r u i t ) 1 , which is the last character in the string. Exercise 1 Write a function that takes a string as an argument and displays the letters backward, one per line. Another way to write a traversal is with a f o rloop:
f o rc h a ri nf r u i t : p r i n tc h a r

Each time through the loop, the next character in the string is assigned to the variable c h a r . The loop continues until no characters are left.
http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89 2/12

5/3/2014

Strings

The following example shows how to use concatenation (string addition) and a f o rloop to generate an abecedarian series (that is, in alphabetical order). In Robert McCloskeys book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order:
p r e f i x e s=' J K L M N O P Q ' s u f f i x=' a c k ' f o rl e t t e ri np r e f i x e s : p r i n tl e t t e r+s u f f i x

The output is:


J a c k K a c k L a c k M a c k N a c k O a c k P a c k Q a c k

Of course, thats not quite right because Ouack and Quack are misspelled. Exercise 2 Modify the program to fix this error.

8.4 String slices


A segment of a string is called a slice . Selecting a slice is similar to selecting a character:
> > >s=' M o n t yP y t h o n ' > > >p r i n ts [ 0 : 5 ] M o n t y > > >p r i n ts [ 6 : 1 2 ] P y t h o n

The operator [ n : m ]returns the part of the string from the n-eth character to the m-eth character, including the first but excluding the last. This behavior is counterintuitive, but it might help to imagine the indices pointing between the characters, as in Figure 8.1.

Figure 8.1: Slice indices.

http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89

3/12

5/3/2014

Strings

If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string:
> > >f r u i t=' b a n a n a ' > > >f r u i t [ : 3 ] ' b a n ' > > >f r u i t [ 3 : ] ' a n a '

If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:
> > >f r u i t=' b a n a n a ' > > >f r u i t [ 3 : 3 ] ' '

An empty string contains no characters and has length 0, but other than that, it is the same as any other string. Exercise 3 Given that f r u i tis a string, what does f r u i t [ : ]mean?

8.5 Strings are immutable


It is tempting to use the [ ]operator on the left side of an assignment, with the intention of changing a character in a string. For example:
> > >g r e e t i n g=' H e l l o ,w o r l d ! ' > > >g r e e t i n g [ 0 ]=' J ' T y p e E r r o r :o b j e c td o e sn o ts u p p o r ti t e ma s s i g n m e n t

The object in this case is the string and the item is the character you tried to assign. For now, an object is the same thing as a value, but we will refine that definition later. An item is one of the values in a sequence. The reason for the error is that strings are immutable , which means you cant change an existing string. The best you can do is create a new string that is a variation on the original:
> > >g r e e t i n g=' H e l l o ,w o r l d ! ' > > >n e w _ g r e e t i n g=' J '+g r e e t i n g [ 1 : ] > > >p r i n tn e w _ g r e e t i n g J e l l o ,w o r l d !

This example concatenates a new first letter onto a slice of g r e e t i n g . It has no effect on the original string.

8.6 Searching
What does the following function do?
http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89 4/12

5/3/2014

Strings

d e ff i n d ( w o r d ,l e t t e r ) : i n d e x=0 w h i l ei n d e x<l e n ( w o r d ) : i fw o r d [ i n d e x ]= =l e t t e r : r e t u r ni n d e x i n d e x=i n d e x+1 r e t u r n1

In a sense, f i n dis the opposite of the [ ]operator. Instead of taking an index and extracting the corresponding character, it takes a character and finds the index where that character appears. If the character is not found, the function returns 1 . This is the first example we have seen of a r e t u r nstatement inside a loop. If w o r d [ i n d e x ]= =l e t t e r , the function breaks out of the loop and returns immediately. If the character doesnt appear in the string, the program exits the loop normally and returns 1 . This pattern of computationtraversing a sequence and returning when we find what we are looking foris called a search. Exercise 4 Modify f i n dso that it has a third parameter, the index in w o r dwhere it should start looking.

8.7 Looping and counting


The following program counts the number of times the letter aappears in a string:
w o r d=' b a n a n a ' c o u n t=0 f o rl e t t e ri nw o r d : i fl e t t e r= =' a ' : c o u n t=c o u n t+1 p r i n tc o u n t

This program demonstrates another pattern of computation called a counter. The variable c o u n tis initialized to 0 and then incremented each time an ais found. When the loop exits, c o u n tcontains the resultthe total number of a s. Exercise 5 Encapsulate this code in a function named c o u n t , and generalize it so that it accepts the string and the letter as arguments. Exercise 6 Rewrite this function so that instead of traversing the string, it uses the three-parameter version of f i n dfrom the previous section.
http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89 5/12

5/3/2014

Strings

8.8 String methods


A method is similar to a functionit takes arguments and returns a value but the syntax is different. For example, the method u p p e rtakes a string and returns a new string with all uppercase letters: Instead of the function syntax u p p e r ( w o r d ) , it uses the method syntax w o r d . u p p e r ( ) .
> > >w o r d=' b a n a n a ' > > >n e w _ w o r d=w o r d . u p p e r ( ) > > >p r i n tn e w _ w o r d B A N A N A

This form of dot notation specifies the name of the method, u p p e r , and the name of the string to apply the method to, w o r d . The empty parentheses indicate that this method takes no argument. A method call is called an invocation; in this case, we would say that we are invoking u p p e ron the w o r d . As it turns out, there is a string method named f i n dthat is remarkably similar to the function we wrote:
> > >w o r d=' b a n a n a ' > > >i n d e x=w o r d . f i n d ( ' a ' ) > > >p r i n ti n d e x 1

In this example, we invoke f i n don w o r dand pass the letter we are looking for as a parameter. Actually, the f i n dmethod is more general than our function; it can find substrings, not just characters:
> > >w o r d . f i n d ( ' n a ' ) 2

It can take as a second argument the index where it should start:


> > >w o r d . f i n d ( ' n a ' ,3 ) 4

And as a third argument the index where it should stop:


> > >n a m e=' b o b ' > > >n a m e . f i n d ( ' b ' ,1 ,2 ) 1

This search fails because bdoes not appear in the index range from 1to 2(not including 2 ). Exercise 7
http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89 6/12

5/3/2014

Strings

There is a string method called c o u n tthat is similar to the function in the previous exercise. Read the documentation of this method and write an invocation that counts the number of a s in ' b a n a n a ' . Exercise 8 Read the documentation of the string methods at
h t t p : / / d o c s . p y t h o n . o r g / 2 / l i b r a r y / s t d t y p e s . h t m l # s t r i n g m e t h o d s . You might want to experiment with some of them to make sure

you understand how they work. s t r i pand r e p l a c eare particularly useful. The documentation uses a syntax that might be confusing. For example, in f i n d ( s u b [ ,s t a r t [ ,e n d ] ] ) , the brackets indicate optional arguments. So s u bis required, but s t a r tis optional, and if you include s t a r t , then e n dis optional.

8.9 The i noperator


The word i nis a boolean operator that takes two strings and returns T r u eif the first appears as a substring in the second:
> > >' a 'i n' b a n a n a ' T r u e > > >' s e e d 'i n' b a n a n a ' F a l s e

For example, the following function prints all the letters from w o r d 1that also appear in w o r d 2 :
d e fi n _ b o t h ( w o r d 1 ,w o r d 2 ) : f o rl e t t e ri nw o r d 1 : i fl e t t e ri nw o r d 2 : p r i n tl e t t e r

With well-chosen variable names, Python sometimes reads like English. You could read this loop, for (each) letter in (the first) word, if (the) letter (appears) in (the second) word, print (the) letter. Heres what you get if you compare apples and oranges:
> > >i n _ b o t h ( ' a p p l e s ' ,' o r a n g e s ' ) a e s

8.10 String comparison


The relational operators work on strings. To see if two strings are equal:
i fw o r d= =' b a n a n a ' :
http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89 7/12

5/3/2014

Strings

p r i n t' A l lr i g h t ,b a n a n a s . '

Other relational operations are useful for putting words in alphabetical order:
i fw o r d<' b a n a n a ' : p r i n t' Y o u rw o r d , '+w o r d+' ,c o m e sb e f o r eb a n a n a . ' e l i fw o r d>' b a n a n a ' : p r i n t' Y o u rw o r d , '+w o r d+' ,c o m e sa f t e rb a n a n a . ' e l s e : p r i n t' A l lr i g h t ,b a n a n a s . '

Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters, so:
Y o u rw o r d ,P i n e a p p l e ,c o m e sb e f o r eb a n a n a .

A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple.

8.11 Debugging
When you use indices to traverse the values in a sequence, it is tricky to get the beginning and end of the traversal right. Here is a function that is supposed to compare two words and return T r u eif one of the words is the reverse of the other, but it contains two errors:
d e fi s _ r e v e r s e ( w o r d 1 ,w o r d 2 ) : i fl e n ( w o r d 1 )! =l e n ( w o r d 2 ) : r e t u r nF a l s e i=0 j=l e n ( w o r d 2 ) w h i l ej>0 : i fw o r d 1 [ i ]! =w o r d 2 [ j ] : r e t u r nF a l s e i=i + 1 j=j 1 r e t u r nT r u e

The first i fstatement checks whether the words are the same length. If not, we can return F a l s eimmediately and then, for the rest of the function, we can assume that the words are the same length. This is an example of the guardian pattern in Section 6.8.
iand jare indices: itraverses w o r d 1forward

while jtraverses w o r d 2 backward. If we find two letters that dont match, we can return F a l s e immediately. If we get through the whole loop and all the letters match, we return T r u e .
http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89 8/12

5/3/2014

Strings

If we test this function with the words pots and stop, we expect the return value T r u e , but we get an IndexError:
> > >i s _ r e v e r s e ( ' p o t s ' ,' s t o p ' ) . . . F i l e" r e v e r s e . p y " ,l i n e1 5 ,i ni s _ r e v e r s e i fw o r d 1 [ i ]! =w o r d 2 [ j ] : I n d e x E r r o r :s t r i n gi n d e xo u to fr a n g e

For debugging this kind of error, my first move is to print the values of the indices immediately before the line where the error appears.
w h i l ej>0 : p r i n ti ,j #p r i n th e r e

i fw o r d 1 [ i ]! =w o r d 2 [ j ] : r e t u r nF a l s e i=i + 1 j=j 1

Now when I run the program again, I get more information:


> > >i s _ r e v e r s e ( ' p o t s ' ,' s t o p ' ) 04 . . . I n d e x E r r o r :s t r i n gi n d e xo u to fr a n g e

The first time through the loop, the value of jis 4, which is out of range for the string ' p o t s ' . The index of the last character is 3, so the initial value for j should be l e n ( w o r d 2 ) 1 . If I fix that error and run the program again, I get:
> > >i s _ r e v e r s e ( ' p o t s ' ,' s t o p ' ) 03 12 21 T r u e

This time we get the right answer, but it looks like the loop only ran three times, which is suspicious. To get a better idea of what is happening, it is useful to draw a state diagram. During the first iteration, the frame for i s _ r e v e r s eis shows in Figure 8.2.

Figure 8.2: State diagram. I took a little license by arranging the variables in the frame and adding dotted lines to show that the values of iand jindicate characters in w o r d 1and
http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89 9/12

5/3/2014

Strings

w o r d 2 .

Exercise 9 Starting with this diagram, execute the program on paper, changing the values of iand jduring each iteration. Find and fix the second error in this function.

8.12 Glossary
object: Something a variable can refer to. For now, you can use object and value interchangeably. sequence: An ordered set; that is, a set of values where each value is identified by an integer index. item: One of the values in a sequence. index: An integer value used to select an item in a sequence, such as a character in a string. slice: A part of a string specified by a range of indices. empty string: A string with no characters and length 0, represented by two quotation marks. immutable: The property of a sequence whose items cannot be assigned. traverse: To iterate through the items in a sequence, performing a similar operation on each. search: A pattern of traversal that stops when it finds what it is looking for. counter: A variable used to count something, usually initialized to zero and then incremented. method: A function that is associated with an object and called using dot notation. invocation: A statement that calls a method.

8.13 Exercises
http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89 10/12

5/3/2014

Strings

Exercise 10 A string slice can take a third index that specifies the step size; that is, the number of spaces between successive characters. A step size of 2 means every other character; 3 means every third, etc.
> > >f r u i t=' b a n a n a ' > > >f r u i t [ 0 : 5 : 2 ] ' b n n '

A step size of -1 goes through the word backwards, so the slice [ : : 1 ] generates a reversed string. Use this idiom to write a one-line version of i s _ p a l i n d r o m efrom Exercise 6. Exercise 11 The following functions are all intended to check whether a string contains any lowercase letters, but at least some of them are wrong. For each function, describe what the function actually does (assuming that the parameter is a string).
d e fa n y _ l o w e r c a s e 1 ( s ) : f o rci ns : i fc . i s l o w e r ( ) : r e t u r nT r u e e l s e : r e t u r nF a l s e d e fa n y _ l o w e r c a s e 2 ( s ) : f o rci ns : i f' c ' . i s l o w e r ( ) : r e t u r n' T r u e ' e l s e : r e t u r n' F a l s e ' d e fa n y _ l o w e r c a s e 3 ( s ) : f o rci ns : f l a g=c . i s l o w e r ( ) r e t u r nf l a g d e fa n y _ l o w e r c a s e 4 ( s ) : f l a g=F a l s e f o rci ns : f l a g=f l a go rc . i s l o w e r ( ) r e t u r nf l a g d e fa n y _ l o w e r c a s e 5 ( s ) : f o rci ns : i fn o tc . i s l o w e r ( ) : r e t u r nF a l s e r e t u r nT r u e
http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89 11/12

5/3/2014

Strings

Exercise 12 ROT13 is a weak form of encryption that involves rotating each letter in a word by 13 places. To rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary, so A shifted by 3 is D and Z shifted by 1 is A. Write a function called r o t a t e _ w o r dthat takes a string and an integer as parameters, and that returns a new string that contains the letters from the original string rotated by the given amount. For example, cheer rotated by 7 is jolly and melon rotated by -10 is cubed. You might want to use the built-in functions o r d , which converts a character to a numeric code, and c h r , which converts numeric codes to characters. Potentially offensive jokes on the Internet are sometimes encoded in ROT13. If you are not easily offended, find and decode some of them. Solution: h t t p : / / t h i n k p y t h o n . c o m / c o d e / r o t a t e . p y . Buy this book at Amazon.com

http://www.greenteapress.com/thinkpython/html/thinkpython009.html#toc89

12/12