forked from csev/py4e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06-strings.php
More file actions
372 lines (369 loc) · 24 KB
/
06-strings.php
File metadata and controls
372 lines (369 loc) · 24 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
<?php if ( file_exists("../booktop.php") ) {
require_once "../booktop.php";
ob_start();
}?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta name="generator" content="pandoc" />
<title></title>
<style type="text/css">code{white-space: pre;}</style>
</head>
<body>
<h1 id="strings">Strings</h1>
<h2 id="a-string-is-a-sequence">A string is a sequence</h2>
<p> </p>
<p>A string is a <em>sequence</em> of characters. You can access the characters one at a time with the bracket operator:</p>
<pre class="python"><code>>>> fruit = 'banana'
>>> letter = fruit[1]</code></pre>
<p> </p>
<p>The second statement extracts the character at index position 1 from the <code>fruit</code> variable and assigns it to the <code>letter</code> variable.</p>
<p>The expression in brackets is called an <em>index</em>. 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="python"><code>>>> print(letter)
a</code></pre>
<p>For most people, the first letter of "banana" is <code>b</code>, not <code>a</code>. But in Python, the index is an offset from the beginning of the string, and the offset of the first letter is zero.</p>
<pre class="python"><code>>>> letter = fruit[0]
>>> print(letter)
b</code></pre>
<p>So <code>b</code> is the 0th letter ("zero-eth") of "banana", <code>a</code> is the 1th letter ("one-eth"), and <code>n</code> is the 2th ("two-eth") letter.</p>
<div class="figure">
<img src="../images/string.svg" alt="String Indexes" />
<p class="caption">String Indexes</p>
</div>
<p> </p>
<p>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:</p>
<p> </p>
<pre class="python"><code>>>> letter = fruit[1.5]
TypeError: string indices must be integers</code></pre>
<h2 id="getting-the-length-of-a-string-using-len">Getting the length of a string using <code>len</code></h2>
<p> </p>
<p><code>len</code> is a built-in function that returns the number of characters in a string:</p>
<pre class="python"><code>>>> fruit = 'banana'
>>> len(fruit)
6</code></pre>
<p>To get the last letter of a string, you might be tempted to try something like this:</p>
<p> </p>
<pre class="python"><code>>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range</code></pre>
<p>The reason for the <code>IndexError</code> is that there is no letter in <code>'banana'</code> 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 <code>length</code>:</p>
<pre class="python"><code>>>> last = fruit[length-1]
>>> print(last)
a</code></pre>
<p>Alternatively, you can use negative indices, which count backward from the end of the string. The expression <code>fruit[-1]</code> yields the last letter, <code>fruit[-2]</code> yields the second to last, and so on.</p>
<p> </p>
<h2 id="traversal-through-a-string-with-a-loop">Traversal through a string with a loop</h2>
<p> </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 <em>traversal</em>. One way to write a traversal is with a <code>while</code> loop:</p>
<pre class="python"><code>index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1</code></pre>
<p>This loop traverses the string and displays each letter on a line by itself. The loop condition is <code>index \< len(fruit)</code>, so when <code>index</code> 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 <code>len(fruit)-1</code>, which is the last character in the string.</p>
<p>Exercise 1: Write a <code>while</code> 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.</p>
<p>Another way to write a traversal is with a <code>for</code> loop:</p>
<pre class="python"><code>for char in fruit:
print(char)</code></pre>
<p>Each time through the loop, the next character in the string is assigned to the variable <code>char</code>. The loop continues until no characters are left.</p>
<h2 id="string-slices">String slices</h2>
<p> </p>
<p>A segment of a string is called a <em>slice</em>. Selecting a slice is similar to selecting a character:</p>
<pre class="python"><code>>>> s = 'Monty Python'
>>> print(s[0:5])
Monty
>>> print(s[6:12])
Python</code></pre>
<p>The operator returns the part of the string from the "n-eth" character to the "m-eth" character, including the first but excluding the last.</p>
<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="python"><code>>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'</code></pre>
<p>If the first index is greater than or equal to the second the result is an <em>empty string</em>, represented by two quotation marks:</p>
<p></p>
<pre class="python"><code>>>> fruit = 'banana'
>>> fruit[3:3]
''</code></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>Exercise 2: Given that <code>fruit</code> is a string, what does <code>fruit[:]</code> mean?</p>
<p> </p>
<h2 id="strings-are-immutable">Strings are immutable</h2>
<p> </p>
<p>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:</p>
<p> </p>
<pre class="python"><code>>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment</code></pre>
<p>The "object" in this case is the string and the "item" is the character you tried to assign. For now, an <em>object</em> is the same thing as a value, but we will refine that definition later. An <em>item</em> is one of the values in a sequence.</p>
<p> </p>
<p>The reason for the error is that strings are <em>immutable</em>, 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="python"><code>>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print(new_greeting)
Jello, world!</code></pre>
<p>This example concatenates a new first letter onto a slice of <code>greeting</code>. It has no effect on the original string.</p>
<p></p>
<h2 id="looping-and-counting">Looping and counting</h2>
<p> </p>
<p>The following program counts the number of times the letter <code>a</code> appears in a string:</p>
<pre class="python"><code>word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)</code></pre>
<p>This program demonstrates another pattern of computation called a <em>counter</em>. The variable <code>count</code> is initialized to 0 and then incremented each time an <code>a</code> is found. When the loop exits, <code>count</code> contains the result: the total number of <code>a</code>'s.</p>
<p>Exercise 3:</p>
<p></p>
<p>Encapsulate this code in a function named <code>count</code>, and generalize it so that it accepts the string and the letter as arguments.</p>
<h2 id="the-in-operator">The <code>in</code> operator</h2>
<p> </p>
<p>The word <code>in</code> is a boolean operator that takes two strings and returns <code>True</code> if the first appears as a substring in the second:</p>
<pre class="python"><code>>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False</code></pre>
<h2 id="string-comparison">String comparison</h2>
<p> </p>
<p>The comparison operators work on strings. To see if two strings are equal:</p>
<pre class="python"><code>if word == 'banana':
print('All right, bananas.')</code></pre>
<p>Other comparison operations are useful for putting words in alphabetical order:</p>
<pre class="python"><code>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.')</code></pre>
<p>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:</p>
<pre><code>Your word, Pineapple, comes before banana.</code></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 id="string-methods"><code>string</code> methods</h2>
<p>Strings are an example of Python <em>objects</em>. An object contains both data (the actual string itself) and <em>methods</em>, which are effectively functions that are built into the object and are available to any <em>instance</em> of the object.</p>
<p>Python has a function called <code>dir</code> which lists the methods available for an object. The <code>type</code> function shows the type of an object and the <code>dir</code> function shows the available methods.</p>
<pre class="python"><code>>>> stuff = 'Hello world'
>>> type(stuff)
<class 'str'>
>>> dir(stuff)
['capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'maketrans', '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() -> str
Return a capitalized version of S, i.e. make the first character
have upper case and the rest lower case.
>>></code></pre>
<p>While the <code>dir</code> function lists the methods, and you can use <code>help</code> to get some simple documentation on a method, a better source of documentation for string methods would be <a href="https://docs.python.org/3.5/library/stdtypes.html#string-methods" class="uri">https://docs.python.org/3.5/library/stdtypes.html#string-methods</a>.</p>
<p>Calling a <em>method</em> 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.</p>
<p>For example, the method <code>upper</code> takes a string and returns a new string with all uppercase letters:</p>
<p> </p>
<p>Instead of the function syntax <code>upper(word)</code>, it uses the method syntax <code>word.upper()</code>.</p>
<p></p>
<pre class="python"><code>>>> word = 'banana'
>>> new_word = word.upper()
>>> print(new_word)
BANANA</code></pre>
<p>This form of dot notation specifies the name of the method, <code>upper</code>, and the name of the string to apply the method to, <code>word</code>. The empty parentheses indicate that this method takes no argument.</p>
<p></p>
<p>A method call is called an <em>invocation</em>; in this case, we would say that we are invoking <code>upper</code> on the <code>word</code>.</p>
<p></p>
<p>For example, there is a string method named <code>find</code> that searches for the position of one string within another:</p>
<pre class="python"><code>>>> word = 'banana'
>>> index = word.find('a')
>>> print(index)
1</code></pre>
<p>In this example, we invoke <code>find</code> on <code>word</code> and pass the letter we are looking for as a parameter.</p>
<p>The <code>find</code> method can find substrings as well as characters:</p>
<pre class="python"><code>>>> word.find('na')
2</code></pre>
<p>It can take as a second argument the index where it should start:</p>
<p> </p>
<pre class="python"><code>>>> word.find('na', 3)
4</code></pre>
<p>One common task is to remove white space (spaces, tabs, or newlines) from the beginning and end of a string using the <code>strip</code> method:</p>
<pre class="python"><code>>>> line = ' Here we go '
>>> line.strip()
'Here we go'</code></pre>
<p>Some methods such as <em>startswith</em> return boolean values.</p>
<pre class="python"><code>>>> line = 'Have a nice day'
>>> line.startswith('Have')
True
>>> line.startswith('h')
False</code></pre>
<p>You will note that <code>startswith</code> requires case to match, so sometimes we take a line and map it all to lowercase before we do any checking using the <code>lower</code> method.</p>
<pre class="python"><code>>>> line = 'Have a nice day'
>>> line.startswith('h')
False
>>> line.lower()
'have a nice day'
>>> line.lower().startswith('h')
True</code></pre>
<p>In the last example, the method <code>lower</code> is called and then we use <code>startswith</code> to see if the resulting lowercase string starts with the letter "h". As long as we are careful with the order, we can make multiple method calls in a single expression.</p>
<p>Exercise 4:</p>
<p> </p>
<p>There is a string method called <code>count</code> that is similar to the function in the previous exercise. Read the documentation of this method at <a href="https://docs.python.org/3.5/library/stdtypes.html#string-methods" class="uri">https://docs.python.org/3.5/library/stdtypes.html#string-methods</a> and write an invocation that counts the number of times the letter a occurs in "banana".</p>
<h2 id="parsing-strings">Parsing strings</h2>
<p>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:</p>
<p><code>From stephen.marquard@</code><em><code> uct.ac.za</code></em><code> Sat Jan 5 09:14:16 2008</code></p>
<p>and we wanted to pull out only the second half of the address (i.e., <code>uct.ac.za</code>) from each line, we can do this by using the <code>find</code> method and string slicing.</p>
<p>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.</p>
<pre class="python"><code>>>> 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
>>></code></pre>
<p>We use a version of the <code>find</code> method which allows us to specify a position in the string where we want <code>find</code> 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".</p>
<p>The documentation for the <code>find</code> method is available at</p>
<p><a href="https://docs.python.org/3.5/library/stdtypes.html#string-methods" class="uri">https://docs.python.org/3.5/library/stdtypes.html#string-methods</a>.</p>
<h2 id="format-operator">Format operator</h2>
<p> </p>
<p>The <em>format operator</em>, <code>%</code> allows us to construct strings, replacing parts of the strings with the data stored in variables. When applied to integers, <code>%</code> is the modulus operator. But when the first operand is a string, <code>%</code> is the format operator.</p>
<p></p>
<p>The first operand is the <em>format string</em>, which contains one or more <em>format sequences</em> that specify how the second operand is formatted. The result is a string.</p>
<p></p>
<p>For example, the format sequence "%d" means that the second operand should be formatted as an integer (<code>d</code> stands for "decimal"):</p>
<pre class="python"><code>>>> camels = 42
>>> '%d' % camels
'42'</code></pre>
<p>The result is the string "42", which is not to be confused with the integer value <code>42</code>.</p>
<p>A format sequence can appear anywhere in the string, so you can embed a value in a sentence:</p>
<pre class="python"><code>>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'</code></pre>
<p>If there is more than one format sequence in the string, the second argument has to be a tuple<a href="#fn1" class="footnoteRef" id="fnref1"><sup>1</sup></a>. Each format sequence is matched with an element of the tuple, in order.</p>
<p>The following example uses "%d" to format an integer, "%g" to format a floating-point number (don't ask why), and "%s" to format a string:</p>
<pre class="python"><code>>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'</code></pre>
<p>The number of elements in the tuple must match the number of format sequences in the string. The types of the elements also must match the format sequences:</p>
<p> </p>
<pre class="python"><code>>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: %d format: a number is required, not str</code></pre>
<p>In the first example, there aren't enough elements; in the second, the element is the wrong type.</p>
<p>The format operator is powerful, but it can be difficult to use. You can read more about it at</p>
<p><a href="https://docs.python.org/3.5/library/stdtypes.html#printf-style-string-formatting" class="uri">https://docs.python.org/3.5/library/stdtypes.html#printf-style-string-formatting</a>.</p>
<h2 id="debugging">Debugging</h2>
<p></p>
<p>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?"</p>
<p>For example, look at the program which we used to demonstrate the <code>while</code> loop in the chapter on iteration:</p>
<pre class="python"><code>while True:
line = input('> ')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print('Done!')
# Code: http://www.py4e.com/code3/copytildone2.py</code></pre>
<p>Look what happens when the user enters an empty line of input:</p>
<pre class="python"><code>> 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] == '#':
IndexError: string index out of range</code></pre>
<p>The code works fine until it is presented an empty line. Then there is no zero-th character, so we get a traceback. There are two solutions to this to make line three "safe" even if the line is empty.</p>
<p>One possibility is to simply use the <code>startswith</code> method which returns <code>False</code> if the string is empty.</p>
<pre><code> if line.startswith('#'):</code></pre>
<p> </p>
<p>Another way is to safely write the <code>if</code> statement using the <em>guardian</em> pattern and make sure the second logical expression is evaluated only where there is at least one character in the string.:</p>
<pre><code> if len(line) > 0 and line[0] == '#':</code></pre>
<h2 id="glossary">Glossary</h2>
<dl>
<dt>counter</dt>
<dd>A variable used to count something, usually initialized to zero and then incremented.
</dd>
<dt>empty string</dt>
<dd>A string with no characters and length 0, represented by two quotation marks.
</dd>
<dt>format operator</dt>
<dd>An operator, <code>%</code>, 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.
</dd>
<dt>format sequence</dt>
<dd>A sequence of characters in a format string, like <code>%d</code>, that specifies how a value should be formatted.
</dd>
<dt>format string</dt>
<dd>A string, used with the format operator, that contains format sequences.
</dd>
<dt>flag</dt>
<dd>A boolean variable used to indicate whether a condition is true or false.
</dd>
<dt>invocation</dt>
<dd>A statement that calls a method.
</dd>
<dt>immutable</dt>
<dd>The property of a sequence whose items cannot be assigned.
</dd>
<dt>index</dt>
<dd>An integer value used to select an item in a sequence, such as a character in a string.
</dd>
<dt>item</dt>
<dd>One of the values in a sequence.
</dd>
<dt>method</dt>
<dd>A function that is associated with an object and called using dot notation.
</dd>
<dt>object</dt>
<dd>Something a variable can refer to. For now, you can use "object" and "value" interchangeably.
</dd>
<dt>search</dt>
<dd>A pattern of traversal that stops when it finds what it is looking for.
</dd>
<dt>sequence</dt>
<dd>An ordered set; that is, a set of values where each value is identified by an integer index.
</dd>
<dt>slice</dt>
<dd>A part of a string specified by a range of indices.
</dd>
<dt>traverse</dt>
<dd>To iterate through the items in a sequence, performing a similar operation on each.
</dd>
</dl>
<h2 id="exercises">Exercises</h2>
<p>Exercise 5: Take the following Python code that stores a string:`</p>
<p><code>str = 'X-DSPAM-Confidence:</code><strong><code>0.8475</code></strong><code>'</code></p>
<p>Use <code>find</code> and string slicing to extract the portion of the string after the colon character and then use the <code>float</code> function to convert the extracted string into a floating point number.</p>
<p>Exercise 6:</p>
<p> </p>
<p>Read the documentation of the string methods at</p>
<p><a href="https://docs.python.org/3.5/library/stdtypes.html#string-methods" class="uri">https://docs.python.org/3.5/library/stdtypes.html#string-methods</a></p>
<p>You might want to experiment with some of them to make sure you understand how they work. <code>strip</code> and <code>replace</code> are particularly useful.</p>
<p>The documentation uses a syntax that might be confusing. For example, in <code>find(sub[, start[, end]])</code>, the brackets indicate optional arguments. So <code>sub</code> is required, but <code>start</code> is optional, and if you include <code>start</code>, then <code>end</code> is optional.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>A tuple is a sequence of comma-separated values inside a pair of parenthesis. We will cover tuples in Chapter 10<a href="#fnref1">↩</a></p></li>
</ol>
</div>
</body>
</html>
<?php if ( file_exists("../bookfoot.php") ) {
$HTML_FILE = basename(__FILE__);
$HTML = ob_get_contents();
ob_end_clean();
require_once "../bookfoot.php";
}?>