forked from bailiangrui/git-basics-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththinkpython2009.html
More file actions
626 lines (589 loc) · 38.6 KB
/
thinkpython2009.html
File metadata and controls
626 lines (589 loc) · 38.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<meta name="generator" content="hevea 2.09">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="thinkpython2.css">
<title>Strings</title>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><strong>Think Python</strong> - How to Think like a Computer Scientist (2e) <em>by Allen B. Downey</em></a>
</div>
<div>
<ul class="nav navbar-nav navbar-right">
<li><a href="http://greenteapress.com/thinkpython2/html/index.html"><span class="glyphicon glyphicon glyphicon-book" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2008.html"><span class="glyphicon glyphicon glyphicon-menu-left" aria-hidden="true"></span></a></li>
<li><a href="index.html"><span class="glyphicon glyphicon glyphicon-home" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2010.html"><span class="glyphicon glyphicon glyphicon-menu-right" aria-hidden="true"></span></a></li>
<li><a href="http://amzn.to/1VUYQUU"><span class="glyphicon glyphicon glyphicon-shopping-cart" aria-hidden="true"></span></a></li>
</ul>
<div>
</div><!-- /.container-fluid -->
</nav>
<table>
<tr>
<td valign="top" width="100" bgcolor="#b6459a" id="col-left">
</td>
<td valign="top" id="content">
<p>
<h1 class="chapter" id="sec91">Chapter 8  Strings</h1>
<p>
<a id="strings"></a></p><p>Strings are not like integers, floats, and booleans. A string
is a <span class="c010">sequence</span>, which means it is
an ordered collection of other values. In this chapter you’ll see
how to access the characters that make up a string, and you’ll
learn about some of the methods strings provide.
<a id="hevea_default541"></a></p>
<h2 class="section" id="sec92">8.1  A string is a sequence</h2>
<p><a id="hevea_default542"></a>
<a id="hevea_default543"></a>
<a id="hevea_default544"></a>
<a id="hevea_default545"></a>
A string is a sequence of characters.
You can access the characters one at a time with the
bracket operator:</p><pre class="verbatim">>>> fruit = 'banana'
>>> letter = fruit[1]
</pre><p>The second statement selects character number 1 from <span class="c004">fruit</span> and assigns it to <span class="c004">letter</span>.
<a id="hevea_default546"></a></p><p>The expression in brackets is called an <span class="c010">index</span>.
The index indicates which character in the sequence you
want (hence the name).</p><p>But you might not get what you expect:</p><pre class="verbatim">>>> letter
'a'
</pre><p>For most people, the first letter of <code>'banana'</code> is <span class="c004">b</span>, not
<span class="c004">a</span>. But for computer scientists, the index is an offset from the
beginning of the string, and the offset of the first letter is zero.</p><pre class="verbatim">>>> letter = fruit[0]
>>> letter
'b'
</pre><p>So <span class="c004">b</span> is the 0th letter (“zero-eth”) of <code>'banana'</code>, <span class="c004">a</span> is the 1th letter (“one-eth”), and <span class="c004">n</span> is the 2th letter
(“two-eth”). <a id="hevea_default547"></a> <a id="hevea_default548"></a></p><p>As an index you can use an expression that contains variables and
operators:
<a id="hevea_default549"></a></p><pre class="verbatim">>>> i = 1
>>> fruit[i]
'a'
>>> fruit[i+1]
'n'
</pre><p>But the value of the index has to be an integer. Otherwise you
get:
<a id="hevea_default550"></a>
<a id="hevea_default551"></a></p><pre class="verbatim">>>> letter = fruit[1.5]
TypeError: string indices must be integers
</pre>
<h2 class="section" id="sec93">8.2  <span class="c004">len</span></h2>
<p>
<a id="hevea_default552"></a>
<a id="hevea_default553"></a></p><p><span class="c004">len</span> is a built-in function that returns the number of characters
in a string:</p><pre class="verbatim">>>> fruit = 'banana'
>>> len(fruit)
6
</pre><p>To get the last letter of a string, you might be tempted to try something
like this:
<a id="hevea_default554"></a>
<a id="hevea_default555"></a></p><pre class="verbatim">>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range
</pre><p>The reason for the <span class="c004">IndexError</span> is that there is no letter in <span class="c004">’banana’</span> 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 <span class="c004">length</span>:</p><pre class="verbatim">>>> last = fruit[length-1]
>>> last
'a'
</pre><p>Or you can use negative indices, which count backward from
the end of the string. The expression <span class="c004">fruit[-1]</span> yields the last
letter, <span class="c004">fruit[-2]</span> yields the second to last, and so on.
<a id="hevea_default556"></a>
<a id="hevea_default557"></a></p>
<h2 class="section" id="sec94">8.3  Traversal with a <span class="c004">for</span> loop</h2>
<p>
<a id="for"></a>
<a id="hevea_default558"></a>
<a id="hevea_default559"></a>
<a id="hevea_default560"></a>
<a id="hevea_default561"></a>
<a id="hevea_default562"></a>
<a id="hevea_default563"></a></p><p>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 <span class="c010">traversal</span>. One way to write a traversal
is with a <span class="c004">while</span> loop:</p><pre class="verbatim">index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
</pre><p>This loop traverses the string and displays each letter on a line by
itself. The loop condition is <span class="c004">index < len(fruit)</span>, so
when <span class="c004">index</span> is equal to the length of the string, the
condition is false, and the body of the loop doesn’t run. The
last character accessed is the one with the index <span class="c004">len(fruit)-1</span>,
which is the last character in the string.</p><p>As an exercise, write a function that takes a string as an argument
and displays the letters backward, one per line.</p><p>Another way to write a traversal is with a <span class="c004">for</span> loop:</p><pre class="verbatim">for letter in fruit:
print(letter)
</pre><p>Each time through the loop, the next character in the string is assigned
to the variable <span class="c004">letter</span>. The loop continues until no characters are
left.
<a id="hevea_default564"></a>
<a id="hevea_default565"></a>
<a id="hevea_default566"></a></p><p>The following example shows how to use concatenation (string addition)
and a <span class="c004">for</span> loop to generate an abecedarian series (that is, in
alphabetical order). In Robert McCloskey’s book <em>Make
Way for Ducklings</em>, the names of the ducklings are Jack, Kack, Lack,
Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in
order:</p><pre class="verbatim">prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
print(letter + suffix)
</pre><p>The output is:</p><pre class="verbatim">Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack
</pre><p>Of course, that’s not quite right because “Ouack” and “Quack” are
misspelled. As an exercise, modify the program to fix this error.</p>
<h2 class="section" id="sec95">8.4  String slices</h2>
<p>
<a id="slice"></a>
<a id="hevea_default567"></a> <a id="hevea_default568"></a> <a id="hevea_default569"></a>
<a id="hevea_default570"></a> <a id="hevea_default571"></a></p><p>A segment of a string is called a <span class="c010">slice</span>. Selecting a slice is
similar to selecting a character:</p><pre class="verbatim">>>> s = 'Monty Python'
>>> s[0:5]
'Monty'
>>> s[6:12]
'Python'
</pre><p>The operator <span class="c004">[n:m]</span> 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 <em>between</em> the
characters, as in Figure <a href="thinkpython2009.html#fig.banana">8.1</a>.</p><blockquote class="figure"><div class="center"><hr class="c019"></div>
<div class="center"><img src="images/thinkpython2009.png"></div>
<div class="caption"><table class="c001 cellpading0"><tr><td class="c018">Figure 8.1: Slice indices.</td></tr>
</table></div>
<a id="fig.banana"></a>
<div class="center"><hr class="c019"></div></blockquote><p>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:</p><pre class="verbatim">>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
</pre><p>If the first index is greater than or equal to the second the result
is an <span class="c010">empty string</span>, represented by two quotation marks:
<a id="hevea_default572"></a></p><pre class="verbatim">>>> fruit = 'banana'
>>> fruit[3:3]
''
</pre><p>An empty string contains no characters and has length 0, but other
than that, it is the same as any other string.</p><p>Continuing this example, what do you think
<span class="c004">fruit[:]</span> means? Try it and see.
<a id="hevea_default573"></a>
<a id="hevea_default574"></a></p>
<h2 class="section" id="sec96">8.5  Strings are immutable</h2>
<p>
<a id="hevea_default575"></a>
<a id="hevea_default576"></a>
<a id="hevea_default577"></a></p><p>It is tempting to use the <span class="c004">[]</span> operator on the left side of an
assignment, with the intention of changing a character in a string.
For example:
<a id="hevea_default578"></a>
<a id="hevea_default579"></a></p><pre class="verbatim">>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment
</pre><p>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 (Section <a href="thinkpython2011.html#equivalence">10.10</a>).
<a id="hevea_default580"></a>
<a id="hevea_default581"></a>
<a id="hevea_default582"></a>
<a id="hevea_default583"></a>
<a id="hevea_default584"></a></p><p>The reason for the error is that
strings are <span class="c010">immutable</span>, which means you can’t change an
existing string. The best you can do is create a new string
that is a variation on the original:</p><pre class="verbatim">>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> new_greeting
'Jello, world!'
</pre><p>This example concatenates a new first letter onto
a slice of <span class="c004">greeting</span>. It has no effect on
the original string.
<a id="hevea_default585"></a></p>
<h2 class="section" id="sec97">8.6  Searching</h2>
<p>
<a id="find"></a></p><p>What does the following function do?
<a id="hevea_default586"></a>
<a id="hevea_default587"></a></p><pre class="verbatim">def find(word, letter):
index = 0
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
</pre><p>In a sense, <span class="c004">find</span> is the inverse of the <span class="c004">[]</span> 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 <span class="c004">-1</span>.</p><p>This is the first example we have seen of a <span class="c004">return</span> statement
inside a loop. If <span class="c004">word[index] == letter</span>, the function breaks
out of the loop and returns immediately.</p><p>If the character doesn’t appear in the string, the program
exits the loop normally and returns <span class="c004">-1</span>.</p><p>This pattern of computation—traversing a sequence and returning
when we find what we are looking for—is called a <span class="c010">search</span>.
<a id="hevea_default588"></a>
<a id="hevea_default589"></a>
<a id="hevea_default590"></a></p><p>As an exercise, modify <span class="c004">find</span> so that it has a
third parameter, the index in <span class="c004">word</span> where it should start
looking.</p>
<h2 class="section" id="sec98">8.7  Looping and counting</h2>
<p>
<a id="counter"></a>
<a id="hevea_default591"></a>
<a id="hevea_default592"></a>
<a id="hevea_default593"></a>
<a id="hevea_default594"></a></p><p>The following program counts the number of times the letter <span class="c004">a</span>
appears in a string:</p><pre class="verbatim">word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
</pre><p>This program demonstrates another pattern of computation called a <span class="c010">counter</span>. The variable <span class="c004">count</span> is initialized to 0 and then
incremented each time an <span class="c004">a</span> is found.
When the loop exits, <span class="c004">count</span>
contains the result—the total number of <span class="c004">a</span>’s.</p><p><a id="hevea_default595"></a>
As an exercise, encapsulate this code in a function named <span class="c004">count</span>, and generalize it so that it accepts the string and the
letter as arguments.</p><p>Then rewrite the function so that instead of
traversing the string, it uses the three-parameter version of <span class="c004">find</span> from the previous section.</p>
<h2 class="section" id="sec99">8.8  String methods</h2>
<p>
<a id="optional"></a></p><p>Strings provide methods that perform a variety of useful operations.
A method is similar to a function—it takes arguments and
returns a value—but the syntax is different. For example, the
method <span class="c004">upper</span> takes a string and returns a new string with
all uppercase letters.
<a id="hevea_default596"></a>
<a id="hevea_default597"></a></p><p>Instead of the function syntax <span class="c004">upper(word)</span>, it uses
the method syntax <span class="c004">word.upper()</span>.</p><pre class="verbatim">>>> word = 'banana'
>>> new_word = word.upper()
>>> new_word
'BANANA'
</pre><p>This form of dot notation specifies the name of the method, <span class="c004">upper</span>, and the name of the string to apply the method to, <span class="c004">word</span>. The empty parentheses indicate that this method takes no
arguments.
<a id="hevea_default598"></a>
<a id="hevea_default599"></a></p><p>A method call is called an <span class="c010">invocation</span>; in this case, we would
say that we are invoking <span class="c004">upper</span> on <span class="c004">word</span>.
<a id="hevea_default600"></a></p><p>As it turns out, there is a string method named <span class="c004">find</span> that
is remarkably similar to the function we wrote:</p><pre class="verbatim">>>> word = 'banana'
>>> index = word.find('a')
>>> index
1
</pre><p>In this example, we invoke <span class="c004">find</span> on <span class="c004">word</span> and pass
the letter we are looking for as a parameter.</p><p>Actually, the <span class="c004">find</span> method is more general than our function;
it can find substrings, not just characters:</p><pre class="verbatim">>>> word.find('na')
2
</pre><p>By default, <span class="c004">find</span> starts at the beginning of the string, but
it can take a second argument, the index where it should start:
<a id="hevea_default601"></a>
<a id="hevea_default602"></a></p><pre class="verbatim">>>> word.find('na', 3)
4
</pre><p>This is an example of an <span class="c010">optional argument</span>;
<span class="c004">find</span> can
also take a third argument, the index where it should stop:</p><pre class="verbatim">>>> name = 'bob'
>>> name.find('b', 1, 2)
-1
</pre><p>This search fails because <span class="c004">b</span> does not
appear in the index range from <span class="c004">1</span> to <span class="c004">2</span>, not including <span class="c004">2</span>. Searching up to, but not including, the second index makes
<span class="c004">find</span> consistent with the slice operator.</p>
<h2 class="section" id="sec100">8.9  The <span class="c004">in</span> operator</h2>
<p>
<a id="inboth"></a>
<a id="hevea_default603"></a>
<a id="hevea_default604"></a>
<a id="hevea_default605"></a>
<a id="hevea_default606"></a></p><p>The word <span class="c004">in</span> is a boolean operator that takes two strings and
returns <span class="c004">True</span> if the first appears as a substring in the second:</p><pre class="verbatim">>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
</pre><p>For example, the following function prints all the
letters from <span class="c004">word1</span> that also appear in <span class="c004">word2</span>:</p><pre class="verbatim">def in_both(word1, word2):
for letter in word1:
if letter in word2:
print(letter)
</pre><p>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.”</p><p>Here’s what you get if you compare apples and oranges:</p><pre class="verbatim">>>> in_both('apples', 'oranges')
a
e
s
</pre>
<h2 class="section" id="sec101">8.10  String comparison</h2>
<p>
<a id="hevea_default607"></a>
<a id="hevea_default608"></a></p><p>The relational operators work on strings. To see if two strings are equal:</p><pre class="verbatim">if word == 'banana':
print('All right, bananas.')
</pre><p>Other relational operations are useful for putting words in alphabetical
order:</p><pre class="verbatim">if word < 'banana':
print('Your word, ' + word + ', comes before banana.')
elif word > 'banana':
print('Your word, ' + word + ', comes after banana.')
else:
print('All right, bananas.')
</pre><p>Python does not handle uppercase and lowercase letters the same way
people do. All the uppercase letters come before all the
lowercase letters, so:</p><pre class="verbatim">Your word, Pineapple, comes before banana.
</pre><p>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.</p>
<h2 class="section" id="sec102">8.11  Debugging</h2>
<p>
<a id="hevea_default609"></a>
<a id="hevea_default610"></a></p><p>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 <span class="c004">True</span> if one of the words is the reverse
of the other, but it contains two errors:</p><pre class="verbatim">def is_reverse(word1, word2):
if len(word1) != len(word2):
return False
i = 0
j = len(word2)
while j > 0:
if word1[i] != word2[j]:
return False
i = i+1
j = j-1
return True
</pre><p>The first <span class="c004">if</span> statement checks whether the words are the
same length. If not, we can return <span class="c004">False</span> immediately.
Otherwise, 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 <a href="thinkpython2007.html#guardian">6.8</a>.
<a id="hevea_default611"></a>
<a id="hevea_default612"></a>
<a id="hevea_default613"></a></p><p><span class="c004">i</span> and <span class="c004">j</span> are indices: <span class="c004">i</span> traverses <span class="c004">word1</span>
forward while <span class="c004">j</span> traverses <span class="c004">word2</span> backward. If we find
two letters that don’t match, we can return <span class="c004">False</span> immediately.
If we get through the whole loop and all the letters match, we
return <span class="c004">True</span>.</p><p>If we test this function with the words “pots” and “stop”, we
expect the return value <span class="c004">True</span>, but we get an IndexError:
<a id="hevea_default614"></a>
<a id="hevea_default615"></a></p><pre class="verbatim">>>> is_reverse('pots', 'stop')
...
File "reverse.py", line 15, in is_reverse
if word1[i] != word2[j]:
IndexError: string index out of range
</pre><p>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.</p><pre class="verbatim"> while j > 0:
print(i, j) # print here
if word1[i] != word2[j]:
return False
i = i+1
j = j-1
</pre><p>Now when I run the program again, I get more information:</p><pre class="verbatim">>>> is_reverse('pots', 'stop')
0 4
...
IndexError: string index out of range
</pre><p>The first time through the loop, the value of <span class="c004">j</span> is 4,
which is out of range for the string <code>'pots'</code>.
The index of the last character is 3, so the
initial value for <span class="c004">j</span> should be <span class="c004">len(word2)-1</span>.</p><p>If I fix that error and run the program again, I get:</p><pre class="verbatim">>>> is_reverse('pots', 'stop')
0 3
1 2
2 1
True
</pre><p>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 <code>is_reverse</code> is shown in
Figure <a href="thinkpython2009.html#fig.state4">8.2</a>. <a id="hevea_default616"></a> <a id="hevea_default617"></a></p><blockquote class="figure"><div class="center"><hr class="c019"></div>
<div class="center"><img src="images/thinkpython2010.png"></div>
<div class="caption"><table class="c001 cellpading0"><tr><td class="c018">Figure 8.2: State diagram.</td></tr>
</table></div>
<a id="fig.state4"></a>
<div class="center"><hr class="c019"></div></blockquote><p>I took some license by arranging the variables in the frame
and adding dotted lines to show that the values of <span class="c004">i</span> and
<span class="c004">j</span> indicate characters in <span class="c004">word1</span> and <span class="c004">word2</span>.</p><p>Starting with this diagram, run the program on paper, changing the
values of <span class="c004">i</span> and <span class="c004">j</span> during each iteration. Find and fix the
second error in this function.
<a id="isreverse"></a></p>
<h2 class="section" id="sec103">8.12  Glossary</h2>
<dl class="description"><dt class="dt-description"><span class="c010">object:</span></dt><dd class="dd-description"> Something a variable can refer to. For now,
you can use “object” and “value” interchangeably.
<a id="hevea_default618"></a></dd><dt class="dt-description"><span class="c010">sequence:</span></dt><dd class="dd-description"> An ordered collection of
values where each value is identified by an integer index.
<a id="hevea_default619"></a></dd><dt class="dt-description"><span class="c010">item:</span></dt><dd class="dd-description"> One of the values in a sequence.
<a id="hevea_default620"></a></dd><dt class="dt-description"><span class="c010">index:</span></dt><dd class="dd-description"> An integer value used to select an item in
a sequence, such as a character in a string. In Python
indices start from 0.
<a id="hevea_default621"></a></dd><dt class="dt-description"><span class="c010">slice:</span></dt><dd class="dd-description"> A part of a string specified by a range of indices.
<a id="hevea_default622"></a></dd><dt class="dt-description"><span class="c010">empty string:</span></dt><dd class="dd-description"> A string with no characters and length 0, represented
by two quotation marks.
<a id="hevea_default623"></a></dd><dt class="dt-description"><span class="c010">immutable:</span></dt><dd class="dd-description"> The property of a sequence whose items cannot
be changed.
<a id="hevea_default624"></a></dd><dt class="dt-description"><span class="c010">traverse:</span></dt><dd class="dd-description"> To iterate through the items in a sequence,
performing a similar operation on each.
<a id="hevea_default625"></a></dd><dt class="dt-description"><span class="c010">search:</span></dt><dd class="dd-description"> A pattern of traversal that stops
when it finds what it is looking for.
<a id="hevea_default626"></a>
<a id="hevea_default627"></a></dd><dt class="dt-description"><span class="c010">counter:</span></dt><dd class="dd-description"> A variable used to count something, usually initialized
to zero and then incremented.
<a id="hevea_default628"></a></dd><dt class="dt-description"><span class="c010">invocation:</span></dt><dd class="dd-description"> A statement that calls a method.
<a id="hevea_default629"></a></dd><dt class="dt-description"><span class="c010">optional argument:</span></dt><dd class="dd-description"> A function or method argument that is not
required.
<a id="hevea_default630"></a>
<a id="hevea_default631"></a></dd></dl>
<h2 class="section" id="sec104">8.13  Exercises</h2>
<div class="theorem"><span class="c010">Exercise 1</span>  
<a id="hevea_default632"></a>
<a id="hevea_default633"></a><p><em>Read the documentation of the string methods at
</em><a href="http://docs.python.org/3/library/stdtypes.html#string-methods"><span class="c004"><em>http://docs.python.org/3/library/stdtypes.html#string-methods</em></span></a><em>.
You might want to experiment with some of them to make sure you
understand how they work. <span class="c004">strip</span> and <span class="c004">replace</span> are
particularly useful.</em></p><p><em>The documentation uses a syntax that might be confusing.
For example, in <code>find(sub[, start[, end]])</code>, the brackets
indicate optional arguments. So <span class="c004">sub</span> is required, but
<span class="c004">start</span> is optional, and if you include <span class="c004">start</span>,
then <span class="c004">end</span> is optional.
</em><a id="hevea_default634"></a>
<a id="hevea_default635"></a></p></div><div class="theorem"><span class="c010">Exercise 2</span>  
<a id="hevea_default636"></a>
<a id="hevea_default637"></a><p><em>There is a string method called <span class="c004">count</span> that is similar
to the function in Section </em><a href="thinkpython2009.html#counter"><em>8.7</em></a><em>. Read the documentation
of this method
and write an invocation that counts the number of <span class="c004">a</span>’s
in <code>'banana'</code>.
</em></p></div><div class="theorem"><span class="c010">Exercise 3</span>  
<a id="hevea_default638"></a>
<a id="hevea_default639"></a>
<a id="hevea_default640"></a><p><em>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.</em></p><pre class="verbatim"><em>>>> fruit = 'banana'
>>> fruit[0:5:2]
'bnn'
</em></pre><p><em>A step size of -1 goes through the word backwards, so
the slice <code>[::-1]</code> generates a reversed string.
</em><a id="hevea_default641"></a></p><p><em>Use this idiom to write a one-line version of <code>is_palindrome</code>
from Exercise </em><a href="thinkpython2007.html#palindrome"><em>3</em></a><em>.
</em></p></div><div class="theorem"><span class="c010">Exercise 4</span>  <p><em>The following functions are all </em>intended<em> 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).</em></p><pre class="verbatim"><em>def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
def any_lowercase2(s):
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
def any_lowercase3(s):
for c in s:
flag = c.islower()
return flag
def any_lowercase4(s):
flag = False
for c in s:
flag = flag or c.islower()
return flag
def any_lowercase5(s):
for c in s:
if not c.islower():
return False
return True
</em></pre></div><div class="theorem"><span class="c010">Exercise 5</span>  
<a id="hevea_default642"></a>
<a id="hevea_default643"></a><p><a id="exrotate"></a><em>
A Caesar cypher is a weak form of encryption that involves “rotating” each
letter by a fixed number of places. To rotate a letter means
to shift it through the alphabet, wrapping around to the beginning if
necessary, so ’A’ rotated by 3 is ’D’ and ’Z’ rotated by 1 is ’A’.</em></p><p><em>To rotate a word, rotate each letter by the same amount.
For example, “cheer” rotated by 7 is “jolly” and “melon” rotated
by -10 is “cubed”. In the movie </em>2001: A Space Odyssey<em>, the
ship computer is called HAL, which is IBM rotated by -1.</em></p><p><em>Write a function called <code>rotate_word</code>
that takes a string and an integer as parameters, and returns
a new string that contains the letters from the original string
rotated by the given amount. </em></p><p><em>You might want to use the built-in function <span class="c004">ord</span>, which converts
a character to a numeric code, and <span class="c004">chr</span>, which converts numeric
codes to characters. Letters of the alphabet are encoded in alphabetical
order, so for example:</em></p><pre class="verbatim"><em>>>> ord('c') - ord('a')
2
</em></pre><p><em>Because <code>'c'</code> is the two-eth letter of the alphabet. But
beware: the numeric codes for upper case letters are different.</em></p><p><em>Potentially offensive jokes on the Internet are sometimes encoded in
ROT13, which is a Caesar cypher with rotation 13. If you are not
easily offended, find and decode some of them. Solution:
</em><a href="http://thinkpython2.com/code/rotate.py"><em><span class="c004">http://thinkpython2.com/code/rotate.py</span></em></a><em>.</em></p></div>
<p>
</td>
<td width=130 valign="top" id="col-right">
<p>
<h4>Are you using one of our books in a class?</h4> We'd like to know
about it. Please consider filling out <a href="http://spreadsheets.google.com/viewform?formkey=dC0tNUZkMjBEdXVoRGljNm9FRmlTMHc6MA" onClick="javascript: pageTracker._trackPageview('/outbound/survey');">this short survey</a>.
<p>
<br>
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491938455/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491938455&linkCode=as2&tag=greenteapre01-20&linkId=2JJH4SWCAVVYSQHO">Think DSP</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491938455" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491938455/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491938455&linkCode=as2&tag=greenteapre01-20&linkId=CTV7PDT7E5EGGJUM"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491938455&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491938455" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491929561/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491929561&linkCode=as2&tag=greenteapre01-20&linkId=ZY6MAYM33ZTNSCNZ">Think Java</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491929561" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491929561/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491929561&linkCode=as2&tag=greenteapre01-20&linkId=PT77ANWARUNNU3UK"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491929561&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491929561" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449370780/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1449370780&linkCode=as2&tag=greenteapre01-20">Think Bayes</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449370780" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449370780/ref=as_li_qf_sp_asin_il?ie=UTF8&camp=1789&creative=9325&creativeASIN=1449370780&linkCode=as2&tag=greenteapre01-20"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1449370780&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449370780" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491939362/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491939362&linkCode=as2&tag=greenteapre01-20&linkId=FJKSQ3IHEMY2F2VA">Think Python 2e</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491939362" width="1" height="1" border="0" alt="">
<p>
<a rel="nofollow" href="http://www.amazon.com/gp/product/1491939362/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491939362&linkCode=as2&tag=greenteapre01-20&linkId=ZZ454DLQ3IXDHNHX"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491939362&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491939362" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1491907339/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491907339&linkCode=as2&tag=greenteapre01-20&linkId=O7WYM6H6YBYUFNWU">Think Stats 2e</a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491907339" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1491907339/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1491907339&linkCode=as2&tag=greenteapre01-20&linkId=JVSYKQHYSUIEYRHL"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1491907339&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://ir-na.amazon-adsystem.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1491907339" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449314635/ref=as_li_tf_tl?ie=UTF8&tag=greenteapre01-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1449314635">Think Complexity</a><img class="c003" src="http://www.assoc-amazon.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449314635" width="1" height="1" border="0" alt="">
<p>
<a href="http://www.amazon.com/gp/product/1449314635/ref=as_li_tf_il?ie=UTF8&camp=1789&creative=9325&creativeASIN=1449314635&linkCode=as2&tag=greenteapre01-20"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=1449314635&Format=_SL160_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=greenteapre01-20"></a><img class="c003" src="http://www.assoc-amazon.com/e/ir?t=greenteapre01-20&l=as2&o=1&a=1449314635" width="1" height="1" border="0" alt="">
</td>
</tr>
</table>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><strong>Think Python</strong> - How to Think like a Computer Scientist (2e) <em>by Allen B. Downey</em></a>
</div>
<div>
<ul class="nav navbar-nav navbar-right">
<li><a href="http://greenteapress.com/thinkpython2/html/index.html"><span class="glyphicon glyphicon glyphicon-book" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2008.html"><span class="glyphicon glyphicon glyphicon-menu-left" aria-hidden="true"></span></a></li>
<li><a href="index.html"><span class="glyphicon glyphicon glyphicon-home" aria-hidden="true"></span></a></li>
<li><a href="thinkpython2010.html"><span class="glyphicon glyphicon glyphicon-menu-right" aria-hidden="true"></span></a></li>
<li><a href="http://amzn.to/1VUYQUU"><span class="glyphicon glyphicon glyphicon-shopping-cart" aria-hidden="true"></span></a></li>
</ul>
<div>
</div><!-- /.container-fluid -->
</nav></body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</html>