forked from csev/py4e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcfbook007.html
More file actions
671 lines (668 loc) · 28.2 KB
/
cfbook007.html
File metadata and controls
671 lines (668 loc) · 28.2 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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="GENERATOR" content="hevea 1.07" />
<title>
Strings
</title>
</head>
<body>
<a href="cfbook006.html"><img src="previous_motif.gif" alt="Previous" /></a>
<a href="index.html"><img src="contents_motif.gif" alt="Up" /></a>
<a href="cfbook008.html"><img src="next_motif.gif" alt="Next" /></a>
<hr />
<h1><font color="black"><a name="htoc72">Chapter 6</a> Strings</font></h1>
<a name="strings"></a>
<a name="toc66"></a>
<h2><font color="black"><a name="htoc73">6.1</a> A string is a sequence</font></h2>
<a name="@default323"></a>
<a name="@default324"></a>
<a name="@default325"></a>
<a name="@default326"></a>
<font color="black">A string is a <b>sequence</b> of characters.
You can access the characters one at a time with the
bracket operator:
</font><pre><font size="4" color="blue">
>>> fruit = 'banana'
>>> letter = fruit[1]
</font></pre><a name="@default327"></a><font color="black">
The second statement extracts the character at index position 1 from the
<tt>fruit</tt> variable and assigns it to <tt>letter</tt> variable. <br />
<br />
The expression in brackets is called an <b>index</b>.
The index indicates which character in the sequence you
want (hence the name).<br />
<br />
But you might not get what you expect:
</font><pre><font size="4" color="blue">
>>> print letter
a
</font></pre><font color="black">For most people, the first letter of <code>'banana'</code> is <tt>b</tt>, not
<tt>a</tt>. But in Python, the index is an offset from the
beginning of the string, and the offset of the first letter is zero.
</font><pre><font size="4" color="blue">
>>> letter = fruit[0]
>>> print letter
b
</font></pre><font color="black">So <tt>b</tt> is the 0th letter ("zero-eth") of <code>'banana'</code>, <tt>a</tt>
is the 1th letter ("one-eth"), and <tt>n</tt> is the 2th ("two-eth")
letter.<br />
</font><div align="center"><font color="black"><img src="cfbook009.png" /></font></div>
<br />
<a name="@default328"></a>
<a name="@default329"></a><br />
<font color="black">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:</font><br />
<br />
<a name="@default330"></a>
<a name="@default331"></a>
<a name="@default332"></a>
<pre><font size="4" color="blue">
>>> letter = fruit[1.5]
TypeError: string indices must be integers
</font></pre>
<a name="toc67"></a>
<h2><font color="black"><a name="htoc74">6.2</a> Getting the length of a string using <tt>len</tt></font></h2>
<a name="@default333"></a>
<a name="@default334"></a>
<font color="black"><tt>len</tt> is a built-in function that returns the number of characters
in a string:
</font><pre><font size="4" color="blue">
>>> fruit = 'banana'
>>> len(fruit)
6
</font></pre><font color="black">To get the last letter of a string, you might be tempted to try something
like this:</font><br />
<br />
<a name="@default335"></a>
<a name="@default336"></a>
<pre><font size="4" color="blue">
>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range
</font></pre><font color="black">The reason for the <tt>IndexError</tt> is that there is no letter in <tt>'banana'</tt> 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 <tt>length</tt>:
</font><pre><font size="4" color="blue">
>>> last = fruit[length-1]
>>> print last
a
</font></pre><font color="black">Alternatively, you can use negative indices, which count backward from
the end of the string. The expression <tt>fruit[-1]</tt> yields the last
letter, <tt>fruit[-2]</tt> yields the second to last, and so on.</font><br />
<br />
<a name="@default337"></a>
<a name="@default338"></a><br />
<br />
<a name="toc68"></a>
<h2><font color="black"><a name="htoc75">6.3</a> Traversal through a string with a loop</font></h2>
<a name="for"></a>
<a name="@default339"></a>
<a name="@default340"></a>
<a name="@default341"></a>
<a name="@default342"></a>
<a name="@default343"></a>
<a name="@default344"></a>
<font color="black">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 <b>traversal</b>. One way to write a traversal
is with a <tt>while</tt> loop:
</font><pre><font size="4" color="blue">
index = 0
while index < len(fruit):
letter = fruit[index]
print letter
index = index + 1
</font></pre><font color="black">This loop traverses the string and displays each letter on a line by
itself. The loop condition is <tt>index < len(fruit)</tt>, so
when <tt>index</tt> is 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 <tt>len(fruit)-1</tt>,
which is the last character in the string.<br />
</font><div align="left"><font color="black"><b>Exercise 1</b> <em>
Write a <tt>while</tt> loop that starts at the last character in the string
and works its way backwards to the first character in the string,
printing each letter on a separate line, except backwards.
</em></font></div><br />
<font color="black">Another way to write a traversal is with a <tt>for</tt> loop:
</font><pre><font size="4" color="blue">
for char in fruit:
print char
</font></pre><font color="black">Each time through the loop, the next character in the string is assigned
to the variable <tt>char</tt>. The loop continues until no characters are
left.</font><br />
<br />
<a name="toc69"></a>
<h2><font color="black"><a name="htoc76">6.4</a> String slices</font></h2>
<a name="slice"></a>
<a name="@default345"></a>
<a name="@default346"></a>
<a name="@default347"></a>
<a name="@default348"></a>
<a name="@default349"></a>
<font color="black">A segment of a string is called a <b>slice</b>. Selecting a slice is
similar to selecting a character:
</font><pre><font size="4" color="blue">
>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:13]
Python
</font></pre><font color="black">The operator <tt>[n:m]</tt> returns the part of the string from the
"n-eth" character to the "m-eth" character, including the first but
excluding the last. <br />
<br />
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:
</font><pre><font size="4" color="blue">
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
</font></pre><font color="black">If the first index is greater than or equal to the second the result
is an <b>empty string</b>, represented by two quotation marks:</font><br />
<br />
<a name="@default350"></a>
<pre><font size="4" color="blue">
>>> fruit = 'banana'
>>> fruit[3:3]
"
</font></pre><font color="black">An empty string contains no characters and has length 0, but other
than that, it is the same as any other string.<br />
</font><div align="left"><font color="black"><b>Exercise 2</b> <em>
Given that <tt>fruit</tt> is a string, what does
<tt>fruit[:]</tt> mean?</em></font><br />
<br />
<a name="@default351"></a>
<a name="@default352"></a></div><br />
<a name="toc70"></a>
<h2><font color="black"><a name="htoc77">6.5</a> Strings are immutable</font></h2>
<a name="@default353"></a>
<a name="@default354"></a>
<a name="@default355"></a>
<font color="black">It is tempting to use the <tt>[]</tt> operator on the left side of an
assignment, with the intention of changing a character in a string.
For example:</font><br />
<br />
<a name="@default356"></a>
<a name="@default357"></a>
<pre><font size="4" color="blue">
>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: object does not support item assignment
</font></pre><font color="black">The "object" in this case is the string and the "item" is
the character you tried to assign. For now, an <b>object</b> is
the same thing as a value, but we will refine that definition
later. An <b>item</b> is one of the values in a sequence.<br />
<br />
<a name="@default358"></a>
<a name="@default359"></a>
<a name="@default360"></a>
<a name="@default361"></a><br />
<br />
The reason for the error is that
strings are <b>immutable</b>, 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:
</font><pre><font size="4" color="blue">
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print new_greeting
Jello, world!
</font></pre><font color="black">This example concatenates a new first letter onto
a slice of <tt>greeting</tt>. It has no effect on
the original string.</font><br />
<br />
<a name="@default362"></a><br />
<br />
<a name="toc71"></a>
<h2><font color="black"><a name="htoc78">6.6</a> Looping and counting</font></h2>
<a name="counter"></a>
<a name="@default363"></a>
<a name="@default364"></a>
<a name="@default365"></a>
<a name="@default366"></a>
<font color="black">The following program counts the number of times the letter <tt>a</tt>
appears in a string:
</font><pre><font size="4" color="blue">
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print count
</font></pre><font color="black">This program demonstrates another pattern of computation called a <b>counter</b>. The variable <tt>count</tt> is initialized to 0 and then
incremented each time an <tt>a</tt> is found.
When the loop exits, <tt>count</tt>
contains the result---the total number of <tt>a</tt>'s.<br />
</font><div align="left"><font color="black"><b>Exercise 3</b>
<a name="@default367"></a><br />
<br />
<em>Encapsulate this code in a function named <tt>count</tt>, and generalize it so that it accepts the string and the
letter as arguments.
</em></font></div><br />
<a name="toc72"></a>
<h2><font color="black"><a name="htoc79">6.7</a> The <tt>in</tt> operator</font></h2>
<a name="inboth"></a>
<a name="@default368"></a>
<a name="@default369"></a>
<a name="@default370"></a>
<a name="@default371"></a>
<font color="black">The word <tt>in</tt> is a boolean operator that takes two strings and
returns <tt>True</tt> if the first appears as a substring in the second:
</font><pre><font size="4" color="blue">
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
</font></pre>
<a name="toc73"></a>
<h2><font color="black"><a name="htoc80">6.8</a> String comparison</font></h2>
<a name="@default372"></a>
<a name="@default373"></a>
<font color="black">The comparison operators work on strings. To see if two strings are equal:
</font><pre><font size="4" color="blue">
if word == 'banana':
print 'All right, bananas.'
</font></pre><font color="black">Other comparison operations are useful for putting words in alphabetical
order:
</font><pre><font size="4" color="blue">
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.'
</font></pre><font color="black">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:
</font><pre><font size="4" color="blue">
Your word, Pineapple, comes before banana.
</font></pre><font color="black">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.</font><br />
<br />
<a name="toc74"></a>
<h2><font color="black"><a name="htoc81">6.9</a> <tt>string</tt> methods</font></h2>
<font color="black">Strings are an example of Python <b>objects</b>. An object contains
both data (the actual string itself) as well as <b>methods</b>, which
are effectively functions which that are built into the object and
are available to any <b>instance</b> of the object.<br />
<br />
Python has a function called <tt>dir</tt> that lists the methods available
for an object. The <tt>type</tt> function shows the type of an object
and the <tt>dir</tt> function shows the available methods.
</font><pre><font size="4" color="blue">
>>> stuff = 'Hello world'
>>> type(stuff)
<type 'str'>
>>> dir(stuff)
['capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'index',
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'partition', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']
>>> help(str.capitalize)
Help on method_descriptor:
capitalize(...)
S.capitalize() -> string
Return a copy of the string S with only its first character
capitalized.
>>>
</font></pre>
<font color="black">While the <tt>dir</tt> function lists the methods, and you
can use <tt>help</tt> to get some simple documentation on a method,
a better source of documentation for string methods would be
<tt>docs.python.org/library/string.html</tt>.<br />
<br />
Calling a <b>method</b> is similar to calling a function---it
takes arguments and
returns a value---but the syntax is different. We call a method
by appending the method name to the variable name using the period
as a delimiter.<br />
<br />
For example, the
method <tt>upper</tt> takes a string and returns a new string with
all uppercase letters:<br />
<br />
<a name="@default374"></a>
<a name="@default375"></a><br />
<br />
Instead of the function syntax <tt>upper(word)</tt>, it uses
the method syntax <tt>word.upper()</tt>.</font><br />
<br />
<a name="@default376"></a>
<pre><font size="4" color="blue">
>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA
</font></pre><font color="black">This form of dot notation specifies the name of the method, <tt>upper</tt>, and the name of the string to apply the method to, <tt>word</tt>. The empty parentheses indicate that this method takes no
argument.<br />
<br />
<a name="@default377"></a><br />
<br />
A method call is called an <b>invocation</b>; in this case, we would
say that we are invoking <tt>upper</tt> on the <tt>word</tt>.<br />
<br />
<a name="@default378"></a><br />
<br />
As it turns out, there is a string method named <tt>find</tt> that
is remarkably similar to the function we wrote:
</font><pre><font size="4" color="blue">
>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1
</font></pre><font color="black">In this example, we invoke <tt>find</tt> on <tt>word</tt> and pass
the letter we are looking for as a parameter.<br />
<br />
Actually, the <tt>find</tt> method is more general than our function;
it can find substrings, not just characters:
</font><pre><font size="4" color="blue">
>>> word.find('na')
2
</font></pre><font color="black">It can take as a second argument the index where it should start:</font><br />
<br />
<a name="@default379"></a>
<a name="@default380"></a>
<pre><font size="4" color="blue">
>>> word.find('na', 3)
4
</font></pre><font color="black">One common task is to remove white space (spaces, tabs, or newlines) from
the beginning and end of a string using the <tt>strip</tt> method:
</font><pre><font size="4" color="blue">
>>> line = ' Here we go '
>>> line.strip()
'Here we go'
</font></pre><font color="black">Some methods such as <b>startswith</b> return boolean values.
</font><pre><font size="4" color="blue">
>>> line = 'Please have a nice day'
>>> line.startswith('Please')
True
>>> line.startswith('p')
False
</font></pre><font color="black">You will note that <tt>startswith</tt> requires case to match so sometimes
we take a line and map it all to lowercase before we do any checking
using the <tt>lower</tt> method.
</font><pre><font size="4" color="blue">
>>> line = 'Please have a nice day'
>>> line.startswith('p')
False
>>> line.lower()
'please have a nice day'
>>> line.lower().startswith('p')
True
</font></pre><font color="black">In the last example, the method <tt>lower</tt> is called
and then we use <tt>startswith</tt>
to check to see if the resulting lowercase string
starts with the letter "p". As long as we are careful
with the order, we can make multiple method calls in a
single expression.<br />
</font><div align="left"><font color="black"><b>Exercise 4</b>
<a name="@default381"></a>
<a name="@default382"></a><br />
<br />
<em>There is a string method called <tt>count</tt> that is similar
to the function in the previous exercise. Read the documentation
of this method at
<tt>docs.python.org/library/string.html</tt>
and write an invocation that counts the number of times the
letter a occurs
in <code>'banana'</code>.
</em></font></div><br />
<a name="toc75"></a>
<h2><font color="black"><a name="htoc82">6.10</a> Parsing strings</font></h2>
<font color="black">Often, we want to look into a string and find a substring. For example
if we were presented a series of lines formatted as follows:
</font><pre><font size="4" color="blue">
From stephen.marquard@<b> uct.ac.za</b> Sat Jan 5 09:14:16 2008
</font></pre><font size="4">
</font><font size="3" color="black">And we wanted to pull out only the second half of the address (i.e.
<tt>uct.ac.za</tt>) from each line. We can do this by using the <tt>find</tt>
method and string slicing. <br />
<br />
First, we will find the position of the at-sign in the string. Then we will
find the position of the first space <em>after</em> the at-sign. And then we
will use string slicing to extract the portion of the string which we
are looking for.
</font><pre><font size="4" color="blue">
>>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
>>> atpos = data.find('@')
>>> print atpos
21
>>> sppos = data.find(' ',atpos)
>>> print sppos
31
>>> host = data[atpos+1:sppos]
>>> print host
uct.ac.za
>>>
</font></pre><font color="black">We use a version of the <tt>find</tt> method which allows us to specify
a position in the string where we want <tt>find</tt> to start looking.
When we slice, we extract the characters
from "one beyond the at-sign through up to <em>but not including</em> the
space character". <br />
<br />
The documentation for the <tt>find</tt> method is available at
<tt>docs.python.org/library/string.html</tt>.</font><br />
<br />
<a name="toc76"></a>
<h2><font color="black"><a name="htoc83">6.11</a> Format operator</font></h2>
<a name="@default383"></a>
<a name="@default384"></a>
<font color="black">The <b>format operator</b>, <tt>%</tt>
allows us to construct strings, replacing parts of the strings
with the data stored in variables.
When applied to integers, <tt>%</tt> is the modulus operator. But
when the first operand is a string, <tt>%</tt> is the format operator.<br />
<br />
<a name="@default385"></a><br />
<br />
The first operand is the <b>format string</b>, which contains
one or more <b>format sequences</b> that
specify how
the second operand is formatted. The result is a string.<br />
<br />
<a name="@default386"></a><br />
<br />
For example, the format sequence <code>'%d'</code> means that
the second operand should be formatted as an
integer (<tt>d</tt> stands for "decimal"):
</font><pre><font size="4" color="blue">
>>> camels = 42
>>> '%d' % camels
'42'
</font></pre><font color="black">The result is the string <code>'42'</code>, which is not to be confused
with the integer value <tt>42</tt>.<br />
<br />
A format sequence can appear anywhere in the string,
so you can embed a value in a sentence:
</font><pre><font size="4" color="blue">
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
</font></pre><font color="black">If there is more than one format sequence in the string,
the second argument has to be a tuple. Each format sequence is
matched with an element of the tuple, in order.<br />
<br />
The following example uses <code>'%d'</code> to format an integer,
<code>'%g'</code> to format
a floating-point number (don't ask why), and <code>'%s'</code> to format
a string:
</font><pre><font size="4" color="blue">
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'
</font></pre><font color="black">The number of elements in the tuple has to match the number
of format sequences in the string. Also, the types of the
elements have to match the format sequences:</font><br />
<br />
<a name="@default387"></a>
<a name="@default388"></a>
<pre><font size="4" color="blue">
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: illegal argument type for built-in operation
</font></pre><font color="black">In the first example, there aren't enough elements; in the
second, the element is the wrong type.<br />
<br />
The format operator is powerful, but it can be difficult to use. You
can read more about it at
<tt>docs.python.org/lib/typesseq-strings.html</tt>.</font><br />
<br />
<a name="toc77"></a>
<h2><font color="black"><a name="htoc84">6.12</a> Debugging</font></h2>
<a name="@default389"></a>
<font color="black">A skill that you should cultivate as you program is always
asking yourself, "What could go wrong here?" or alternatively,
"What crazy thing might our user do to crash our (seemingly)
perfect program?".<br />
<br />
For example, look at the program which we used to demonstrate
the <tt>while</tt> loop in the chapter on iteration:
</font><pre><font size="4" color="blue">
while True:
line = raw_input('> ')
if line[0] == '#' :
continue
if line == 'done':
break
print line
print 'Done!'
</font></pre><font color="black">Look what happens when the user enters an empty line of input:
</font><pre><font size="4" color="blue">
> hello there
hello there
> # don't print this
> print this!
print this!
>
Traceback (most recent call last):
File "copytildone.py", line 3, in <module>
if line[0] == '#' :
</font></pre><font color="black">The code works fine until it is presented an empty line. Then
there is no zeroth character so we get a traceback. There are two
solutions to this to make line three "safe" even if the line is
empty.<br />
<br />
One possibility is to simply use the <tt>startswith</tt> method
which returns <tt>False</tt> if the string is empty.
</font><pre><font size="4" color="blue">
if line.startswith('#') :
</font></pre><a name="@default390"></a>
<a name="@default391"></a><font color="black">
Another way to safely write the <tt>if</tt> statement using the <b>guardian</b>
pattern and make sure the second logical expression is evaluated
only where there is at least one character in the string.:
</font><pre><font size="4" color="blue">
if len(line) > 0 and line[0] == '#' :
</font></pre>
<a name="toc78"></a>
<h2><font color="black"><a name="htoc85">6.13</a> Glossary</font></h2>
<dl compact="compact"><dt><font color="black"><b>counter:</b></font></dt><dd><font color="black"> A variable used to count something, usually initialized
to zero and then incremented.
</font><a name="@default392"></a><br />
<br />
</dd><dt><font color="black"><b>empty string:</b></font></dt><dd><font color="black"> A string with no characters and length 0, represented
by two quotation marks.
</font><a name="@default393"></a><br />
<br />
</dd><dt><font color="black"><b>format operator:</b></font></dt><dd><font color="black"> An operator, <tt>%</tt>, that takes a format
string and a tuple and generates a string that includes
the elements of the tuple formatted as specified by the format string.
</font><a name="@default394"></a>
<a name="@default395"></a><br />
<br />
</dd><dt><font color="black"><b>format sequence:</b></font></dt><dd><font color="black"> A sequence of characters in a format string,
like <tt>%d</tt>, that specifies how a value should be formatted.
</font><a name="@default396"></a><br />
<br />
</dd><dt><font color="black"><b>format string:</b></font></dt><dd><font color="black"> A string, used with the format operator, that
contains format sequences.
</font><a name="@default397"></a><br />
<br />
</dd><dt><font color="black"><b>flag:</b></font></dt><dd><font color="black"> A boolean variable used to indicate whether a condition
is true.
</font><a name="@default398"></a><br />
<br />
</dd><dt><font color="black"><b>invocation:</b></font></dt><dd><font color="black"> A statement that calls a method.
</font><a name="@default399"></a><br />
<br />
</dd><dt><font color="black"><b>immutable:</b></font></dt><dd><font color="black"> The property of a sequence whose items cannot
be assigned.
</font><a name="@default400"></a><br />
<br />
</dd><dt><font color="black"><b>index:</b></font></dt><dd><font color="black"> An integer value used to select an item in
a sequence, such as a character in a string.
</font><a name="@default401"></a><br />
<br />
</dd><dt><font color="black"><b>item:</b></font></dt><dd><font color="black"> One of the values in a sequence.
</font><a name="@default402"></a><br />
<br />
</dd><dt><font color="black"><b>method:</b></font></dt><dd><font color="black"> A function that is associated with an object and called
using dot notation.
</font><a name="@default403"></a><br />
<br />
</dd><dt><font color="black"><b>object:</b></font></dt><dd><font color="black"> Something a variable can refer to. For now,
you can use "object" and "value" interchangeably.
</font><a name="@default404"></a><br />
<br />
</dd><dt><font color="black"><b>search:</b></font></dt><dd><font color="black"> A pattern of traversal that stops
when it finds what it is looking for.
</font><a name="@default405"></a>
<a name="@default406"></a><br />
<br />
</dd><dt><font color="black"><b>sequence:</b></font></dt><dd><font color="black"> An ordered set; that is, a set of
values where each value is identified by an integer index.
</font><a name="@default407"></a><br />
<br />
</dd><dt><font color="black"><b>slice:</b></font></dt><dd><font color="black"> A part of a string specified by a range of indices.
</font><a name="@default408"></a><br />
<br />
</dd><dt><font color="black"><b>traverse:</b></font></dt><dd><font color="black"> To iterate through the items in a sequence,
performing a similar operation on each.
</font><a name="@default409"></a></dd></dl>
<a name="toc79"></a>
<h2><font color="black"><a name="htoc86">6.14</a> Exercises</font></h2><br />
<div align="left"><font color="black"><b>Exercise 5</b> <em>
Take the following Python code that stores a string:`
</em></font><pre><font size="4" color="blue"><em>
str = 'X-DSPAM-Confidence: <b> 0.8475</b>'
</em></font></pre><font size="4">
</font><font size="3" color="black"><em>Use <tt>find</tt> and string slicing to extract the portion
of the string after the colon character and then use the
<tt>float</tt> function to convert the extracted string
into a floating point number.</em></font></div><br />
<div align="left"><font color="black"><b>Exercise 6</b>
<a name="@default410"></a>
<a name="@default411"></a><br />
<br />
<em>Read the documentation of the string methods at
<tt>docs.python.org/lib/string-methods.html</tt>. You
might want to experiment with some of them to make sure
you understand how they work. <tt>strip</tt> and
<tt>replace</tt> are particularly useful.<br />
<br />
The documentation uses a syntax that might be confusing.
For example, in <code>find(sub[, start[, end]])</code>, the brackets
indicate optional arguments. So <tt>sub</tt> is required, but
<tt>start</tt> is optional, and if you include <tt>start</tt>,
then <tt>end</tt> is optional.
</em></font></div><br />
<hr />
<a href="cfbook006.html"><img src="previous_motif.gif" alt="Previous" /></a>
<a href="index.html"><img src="contents_motif.gif" alt="Up" /></a>
<a href="cfbook008.html"><img src="next_motif.gif" alt="Next" /></a>
</body>
</html>