Archive:Think Python/Strings: Difference between revisions
wikademia>Whiteknight m Think Python: Automatically uploading HTML source of this book from http://www.greenteapress.com/thinkpython/html/. Will convert to wikitext in a separate step |
wikademia>Whiteknight m Partial (mostly) conversion from HTML to Wikitext |
||
| Line 1: | Line 1: | ||
{{Think Python/Page}} | |||
== Chapter 8  Strings == | |||
=== 8.1  A string is a sequence === | |||
A string is a '''sequence''' of characters. | |||
You can access the characters one at a time with the | You can access the characters one at a time with the | ||
bracket operator: | bracket operator: | ||
<PRE CLASS="verbatim">>>> fruit = 'banana' | |||
>>> letter = fruit[1] | >>> letter = fruit[1] | ||
</PRE> | |||
The second statement selects character number 1 from <TT>fruit</TT> and assigns it to <TT>letter</TT>. | |||
The expression in brackets is called an '''index'''. | |||
The index indicates which character in the sequence you | The index indicates which character in the sequence you | ||
want (hence the name). | want (hence the name). | ||
But you might not get what you expect: | |||
<PRE CLASS="verbatim">>>> print letter | |||
a | a | ||
</PRE> | |||
For most people, the first letter of <CODE>'banana'</CODE> is <TT>b</TT>, not | |||
beginning of the string, and the offset of the first letter is zero. | <TT>a</TT>. But for computer scientists, the index is an offset from the | ||
beginning of the string, and the offset of the first letter is zero. | |||
<PRE CLASS="verbatim">>>> letter = fruit[0] | |||
>>> print letter | >>> print letter | ||
b | b | ||
</PRE> | |||
is the 1th letter (“one-eth”), and | So <TT>b</TT> is the 0th letter (“zero-eth”) of <CODE>'banana'</CODE>, <TT>a</TT> | ||
letter. | is the 1th letter (“one-eth”), and <TT>n</TT> is the 2th (“two-eth”) | ||
letter. | |||
You can use any expression, including variables and operators, as an | |||
index, but the value of the index has to be an integer. Otherwise you | index, but the value of the index has to be an integer. Otherwise you | ||
get: | get: | ||
<PRE CLASS="verbatim">>>> letter = fruit[1.5] | |||
TypeError: string indices must be integers | TypeError: string indices must be integers | ||
</PRE>=== 8.2  <TT>len</TT> === | |||
in a string: | |||
<TT>len</TT> is a built-in function that returns the number of characters | |||
in a string: | |||
<PRE CLASS="verbatim">>>> fruit = 'banana' | |||
>>> len(fruit) | >>> len(fruit) | ||
6 | 6 | ||
</PRE> | |||
like this: | To get the last letter of a string, you might be tempted to try something | ||
like this: | |||
<PRE CLASS="verbatim">>>> length = len(fruit) | |||
>>> last = fruit[length] | >>> last = fruit[length] | ||
IndexError: string index out of range | IndexError: string index out of range | ||
</PRE> | |||
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 | six letters are numbered 0 to 5. To get the last character, you have | ||
to subtract 1 from | to subtract 1 from <TT>length</TT>: | ||
<PRE CLASS="verbatim">>>> last = fruit[length-1] | |||
>>> print last | >>> print last | ||
a | a | ||
</PRE> | |||
the end of the string. The expression | Alternatively, you can use negative indices, which count backward from | ||
letter, | 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. | |||
=== 8.3  Traversal with a <TT>for</TT> loop === | |||
A lot of computations involve processing a string one character at a | |||
time. Often they start at the beginning, select each character in | time. Often they start at the beginning, select each character in | ||
turn, do something to it, and continue until the end. This pattern of | turn, do something to it, and continue until the end. This pattern of | ||
processing is called a | processing is called a '''traversal'''. One way to write a traversal | ||
is with a | is with a <TT>while</TT> loop: | ||
<PRE CLASS="verbatim">index = 0 | |||
while index < len(fruit): | while index < len(fruit): | ||
letter = fruit[index] | letter = fruit[index] | ||
print letter | print letter | ||
index = index + 1 | index = index + 1 | ||
</PRE> | |||
itself. The loop condition is | This loop traverses the string and displays each letter on a line by | ||
when | 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 | condition is false, and the body of the loop is not executed. The | ||
last character accessed is the one with the index | last character accessed is the one with the index <TT>len(fruit)-1</TT>, | ||
which is the last character in the string. | which is the last character in the string. | ||
<DIV CLASS="theorem">'''Exercise 1'''  '' | |||
Write a function that takes a string as an argument | Write a function that takes a string as an argument | ||
and displays the letters backward, one per line. | and displays the letters backward, one per line. | ||
''</DIV> | |||
Another way to write a traversal is with a <TT>for</TT> loop: | |||
<PRE CLASS="verbatim">for char in fruit: | |||
print char | print char | ||
</PRE> | |||
to the variable | Each time through the loop, the next character in the string is assigned | ||
left. | to the variable <TT>char</TT>. The loop continues until no characters are | ||
left. | |||
and a | |||
alphabetical order). In Robert McCloskey’s book | |||
Way for Ducklings | |||
The following example shows how to use concatenation (string addition) | |||
and a <TT>for</TT> loop to generate an abecedarian series (that is, in | |||
alphabetical order). In Robert McCloskey’s book ''Make | |||
Way for Ducklings'', the names of the ducklings are Jack, Kack, Lack, | |||
Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in | Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in | ||
order: | order: | ||
<PRE CLASS="verbatim">prefixes = 'JKLMNOPQ' | |||
suffix = 'ack' | suffix = 'ack' | ||
for letter in prefixes: | for letter in prefixes: | ||
print letter + suffix | print letter + suffix | ||
</PRE> | |||
The output is: | |||
<PRE CLASS="verbatim">Jack | |||
Kack | Kack | ||
Lack | Lack | ||
| Line 106: | Line 151: | ||
Pack | Pack | ||
Qack | Qack | ||
</PRE> | |||
“Quack” are misspelled. | Of course, that’s not quite right because “Ouack” and | ||
“Quack” are misspelled. | |||
<DIV CLASS="theorem">'''Exercise 2'''  '' | |||
Modify the program to fix this error. | Modify the program to fix this error. | ||
''</DIV>=== 8.4  String slices === | |||
similar to selecting a character: | |||
A segment of a string is called a '''slice'''. Selecting a slice is | |||
similar to selecting a character: | |||
<PRE CLASS="verbatim">>>> s = 'Monty Python' | |||
>>> print s[0:5] | >>> print s[0:5] | ||
Monty | Monty | ||
>>> print s[6:13] | >>> print s[6:13] | ||
Python | Python | ||
</PRE> | |||
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 | “n-eth” character to the “m-eth” character, including the first but | ||
excluding the last. This behavior is counterintuitive, but it might | excluding the last. This behavior is counterintuitive, but it might | ||
help to imagine the indices pointing | help to imagine the indices pointing ''between'' the | ||
characters, as in the following diagram: | characters, as in the following diagram: | ||
<DIV CLASS="center"><IMG SRC="book011.png"></DIV> | |||
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 | the beginning of the string. If you omit the second index, the slice | ||
goes to the end of the string: | goes to the end of the string: | ||
<PRE CLASS="verbatim">>>> fruit = 'banana' | |||
>>> fruit[:3] | >>> fruit[:3] | ||
'ban' | 'ban' | ||
>>> fruit[3:] | >>> fruit[3:] | ||
'ana' | 'ana' | ||
</PRE> | |||
is an | If the first index is greater than or equal to the second the result | ||
is an '''empty string''', represented by two quotation marks: | |||
<PRE CLASS="verbatim">>>> fruit = 'banana' | |||
>>> fruit[3:3] | >>> fruit[3:3] | ||
'' | '' | ||
</PRE> | |||
than that, it is the same as any other string. | An empty string contains no characters and has length 0, but other | ||
Given that | than that, it is the same as any other string. | ||
<DIV CLASS="theorem">'''Exercise 3'''  '' | |||
Given that ''''<TT>fruit</TT>'''' is a string, what does | |||
''''<TT>fruit[:]</TT>'''' mean?'' | |||
'' | |||
'' | |||
</DIV>=== 8.5  Strings are immutable === | |||
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. | assignment, with the intention of changing a character in a string. | ||
For example: | For example: | ||
<PRE CLASS="verbatim">>>> greeting = 'Hello, world!' | |||
>>> greeting[0] = 'J' | >>> greeting[0] = 'J' | ||
TypeError: object does not support item assignment | TypeError: object does not support item assignment | ||
</PRE> | |||
the character you tried to assign. For now, an | 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 | the same thing as a value, but we will refine that definition | ||
later. An | later. An '''item''' is one of the values in a sequence. | ||
strings are | |||
The reason for the error is that | |||
strings are '''immutable''', which means you can’t change an | |||
existing string. The best you can do is create a new string | existing string. The best you can do is create a new string | ||
that is a variation on the original: | that is a variation on the original: | ||
<PRE CLASS="verbatim">>>> greeting = 'Hello, world!' | |||
>>> new_greeting = 'J' + greeting[1:] | >>> new_greeting = 'J' + greeting[1:] | ||
>>> print new_greeting | >>> print new_greeting | ||
Jello, world! | Jello, world! | ||
</PRE> | |||
a slice of | This example concatenates a new first letter onto | ||
the original string. | a slice of <TT>greeting</TT>. It has no effect on | ||
the original string. | |||
=== 8.6  Searching === | |||
What does the following function do? | |||
<PRE CLASS="verbatim">def find(word, letter): | |||
index = 0 | index = 0 | ||
while index < len(word): | while index < len(word): | ||
| Line 172: | Line 260: | ||
index = index + 1 | index = index + 1 | ||
return -1 | return -1 | ||
</PRE> | |||
In a sense, <TT>find</TT> is the opposite of the <TT>[]</TT> operator. | |||
Instead of taking an index and extracting the corresponding character, | Instead of taking an index and extracting the corresponding character, | ||
it takes a character and finds the index where that character | it takes a character and finds the index where that character | ||
appears. If the character is not found, the function returns | appears. If the character is not found, the function returns <TT>-1</TT>. | ||
inside a loop. If | |||
out of the loop and returns immediately. | This is the first example we have seen of a <TT>return</TT> statement | ||
exits the loop normally and returns | inside a loop. If <TT>word[index] == letter</TT>, the function breaks | ||
when we find what we are looking for—is a called a | out of the loop and returns immediately. | ||
If the character doesn’t appear in the string, the program | |||
Modify | exits the loop normally and returns <TT>-1</TT>. | ||
third parameter, the index in | |||
This pattern of computation—traversing a sequence and returning | |||
when we find what we are looking for—is a called a '''search'''. | |||
<DIV CLASS="theorem">'''Exercise 4'''  '' | |||
Modify ''''<TT>find</TT>'''' so that it has a | |||
third parameter, the index in ''''<TT>word</TT>'''' where it should start | |||
looking. | looking. | ||
''</DIV>=== 8.7  Looping and counting === | |||
appears in a string: | |||
The following program counts the number of times the letter <TT>a</TT> | |||
appears in a string: | |||
<PRE CLASS="verbatim">word = 'banana' | |||
count = 0 | count = 0 | ||
for letter in word: | for letter in word: | ||
| Line 196: | Line 301: | ||
count = count + 1 | count = count + 1 | ||
print count | print count | ||
</PRE> | |||
incremented each time an | This program demonstrates another pattern of computation called a '''counter'''. The variable <TT>count</TT> is initialized to 0 and then | ||
When the loop exits, | incremented each time an <TT>a</TT> is found. | ||
contains the result—the total number of | When the loop exits, <TT>count</TT> | ||
contains the result—the total number of <TT>a</TT>’s. | |||
<DIV CLASS="theorem">'''Exercise 5'''  '' | |||
'' | |||
''Encapsulate this code in a function named ''''<TT>count</TT>'''', and generalize it so that it accepts the string and the | |||
letter as arguments. | letter as arguments. | ||
'' | |||
</DIV><DIV CLASS="theorem">'''Exercise 6'''  '' | |||
Rewrite this function so that instead of | Rewrite this function so that instead of | ||
traversing the string, it uses the three-parameter version of | traversing the string, it uses the three-parameter version of ''''<TT>find</TT>'''' from the previous section. | ||
''</DIV>=== 8.8  <TT>string</TT> methods === | |||
A '''method''' is similar to a function—it takes arguments and | |||
returns a value—but the syntax is different. For example, the | returns a value—but the syntax is different. For example, the | ||
method | method <TT>upper</TT> takes a string and returns a new string with | ||
all uppercase letters: | all uppercase letters: | ||
the method syntax | |||
Instead of the function syntax <TT>upper(word)</TT>, it uses | |||
the method syntax <TT>word.upper()</TT>. | |||
<PRE CLASS="verbatim">>>> word = 'banana' | |||
>>> new_word = word.upper() | >>> new_word = word.upper() | ||
>>> print new_word | >>> print new_word | ||
BANANA | BANANA | ||
</PRE> | |||
argument. | 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 | ||
say that we are invoking | argument. | ||
is remarkably similar to the function we wrote: | |||
A method call is called an '''invocation'''; in this case, we would | |||
say that we are invoking <TT>upper</TT> on the <TT>word</TT>. | |||
As it turns out, there is a string method named <TT>find</TT> that | |||
is remarkably similar to the function we wrote: | |||
<PRE CLASS="verbatim">>>> word = 'banana' | |||
>>> index = word.find('a') | >>> index = word.find('a') | ||
>>> print index | >>> print index | ||
1 | 1 | ||
</PRE> | |||
the letter we are looking for as a parameter. | In this example, we invoke <TT>find</TT> on <TT>word</TT> and pass | ||
it can find substrings, not just characters: | the letter we are looking for as a parameter. | ||
Actually, the <TT>find</TT> method is more general than our function; | |||
it can find substrings, not just characters: | |||
<PRE CLASS="verbatim">>>> word.find('na') | |||
2 | 2 | ||
</PRE> | |||
It can take as a second argument the index where it should start: | |||
<PRE CLASS="verbatim">>>> word.find('na', 3) | |||
4 | 4 | ||
</PRE> | |||
And as a third argument the index where it should stop: | |||
<PRE CLASS="verbatim">>>> name = 'bob' | |||
>>> name.find('b', 1, 2) | >>> name.find('b', 1, 2) | ||
-1 | -1 | ||
</PRE> | |||
appear in the index range from | This search fails because <TT>b</TT> does not | ||
appear in the index range from <TT>1</TT> to <TT>2</TT> (not including <TT>2</TT>). | |||
<DIV CLASS="theorem">'''Exercise 7'''  '' | |||
'''' | |||
'' | |||
''There is a string method called ''''<TT>count</TT>'''' that is similar | |||
to the function in the previous exercise. Read the documentation | to the function in the previous exercise. Read the documentation | ||
of this method | of this method | ||
and write an invocation that counts the number of | and write an invocation that counts the number of ''''<TT>a</TT>''''s | ||
in | in ''<CODE>'''banana'''</CODE>''. | ||
'' | |||
</DIV>=== 8.9  The <TT>in</TT> operator === | |||
returns | |||
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: | |||
<PRE CLASS="verbatim">>>> 'a' in 'banana' | |||
True | True | ||
>>> 'seed' in 'banana' | >>> 'seed' in 'banana' | ||
False | False | ||
</PRE> | |||
letters from | For example, the following function prints all the | ||
letters from <TT>word1</TT> that also appear in <TT>word2</TT>: | |||
<PRE CLASS="verbatim">def in_both(word1, word2): | |||
for letter in word1: | for letter in word1: | ||
if letter in word2: | if letter in word2: | ||
print letter | print letter | ||
</PRE> | |||
With well-chosen variable names, | |||
Python sometimes reads like English. You could read | Python sometimes reads like English. You could read | ||
this loop, “for (each) letter in (the first) word, if (the) letter | this loop, “for (each) letter in (the first) word, if (the) letter | ||
(appears) in (the second) word, print (the) letter.” | (appears) in (the second) word, print (the) letter.” | ||
Here’s what you get if you compare apples and oranges: | |||
<PRE CLASS="verbatim">>>> in_both('apples', 'oranges') | |||
a | a | ||
e | e | ||
s | s | ||
</PRE>=== 8.10  String comparison === | |||
The comparison operators work on strings. To see if two strings are equal: | |||
<PRE CLASS="verbatim">if word == 'banana': | |||
print 'All right, bananas.' | print 'All right, bananas.' | ||
</PRE> | |||
order: | Other comparison operations are useful for putting words in alphabetical | ||
order: | |||
<PRE CLASS="verbatim">if word < 'banana': | |||
print 'Your word,' + word + ', comes before banana.' | print 'Your word,' + word + ', comes before banana.' | ||
elif word > 'banana': | elif word > 'banana': | ||
| Line 270: | Line 427: | ||
else: | else: | ||
print 'All right, bananas.' | print 'All right, bananas.' | ||
</PRE> | |||
Python does not handle uppercase and lowercase letters the same way | |||
that people do. All the uppercase letters come before all the | that people do. All the uppercase letters come before all the | ||
lowercase letters, so: | lowercase letters, so: | ||
<PRE CLASS="verbatim">Your word, Pineapple, comes before banana. | |||
</PRE> | |||
A common way to address this problem is to convert strings to a | |||
standard format, such as all lowercase, before performing the | standard format, such as all lowercase, before performing the | ||
comparison. Keep that in mind in case you have to defend yourself | comparison. Keep that in mind in case you have to defend yourself | ||
against a man armed with a Pineapple. | against a man armed with a Pineapple. | ||
=== 8.11  Debugging === | |||
When you use indices to traverse the values in a sequence, | |||
it is tricky to get the beginning and end of the traversal | it is tricky to get the beginning and end of the traversal | ||
right. Here is a function that is supposed to compare two | right. Here is a function that is supposed to compare two | ||
words and return | words and return <TT>True</TT> if one of the words is the reverse | ||
of the other, but it contains two errors: | of the other, but it contains two errors: | ||
<PRE CLASS="verbatim">def is_reverse(word1, word2): | |||
if len(word1) != len(word2): | if len(word1) != len(word2): | ||
return False | return False | ||
| Line 295: | Line 461: | ||
return True | return True | ||
</PRE> | |||
same length. If not, we can return | The first <TT>if</TT> statement checks whether the words are the | ||
same length. If not, we can return <TT>False</TT> immediately | |||
and then, for the rest of the function, we can assume that the words | and then, for the rest of the function, we can assume that the words | ||
are the same length. This is an example of the guardian pattern | are the same length. This is an example of the guardian pattern | ||
in Section  | in Section 6.8. | ||
forward while | |||
two letters that don’t match, we can return | |||
<TT>i</TT> and <TT>j</TT> are indices: <TT>i</TT> traverses <TT>word1</TT> | |||
forward while <TT>j</TT> traverses <TT>word2</TT> backward. If we find | |||
two letters that don’t match, we can return <TT>False</TT> immediately. | |||
If we get through the whole loop and all the letters match, we | If we get through the whole loop and all the letters match, we | ||
return | return <TT>True</TT>. | ||
expect the return value | |||
If we test this function with the words “pots” and “stop”, we | |||
expect the return value <TT>True</TT>, but we get an IndexError: | |||
<PRE CLASS="verbatim">>>> is_reverse('pots', 'stop') | |||
... | ... | ||
File "reverse.py", line 15, in is_reverse | File "reverse.py", line 15, in is_reverse | ||
if word1[i] != word2[j]: | if word1[i] != word2[j]: | ||
IndexError: string index out of range | IndexError: string index out of range | ||
</PRE> | |||
For debugging this kind of error, my first move is to | |||
print the values of the indices immediately before the line | print the values of the indices immediately before the line | ||
where the error appears. | where the error appears. | ||
<PRE CLASS="verbatim"> while j > 0: | |||
print i, j # print here | print i, j # print here | ||
| Line 321: | Line 499: | ||
i = i+1 | i = i+1 | ||
j = j-1 | j = j-1 | ||
</PRE> | |||
Now when I run the program again, I get more information: | |||
<PRE CLASS="verbatim">>>> is_reverse('pots', 'stop') | |||
0 4 | 0 4 | ||
... | ... | ||
IndexError: string index out of range | IndexError: string index out of range | ||
</PRE> | |||
which is out of range for the string | The first time through the loop, the value of <TT>j</TT> is 4, | ||
which is out of range for the string <CODE>'pots'</CODE>. | |||
The index of the last character is 3, so the | The index of the last character is 3, so the | ||
initial value for | initial value for <TT>j</TT> should be <TT>len(word2)-1</TT>. | ||
If I fix that error and run the program again, I get: | |||
<PRE CLASS="verbatim">>>> is_reverse('pots', 'stop') | |||
0 3 | 0 3 | ||
1 2 | 1 2 | ||
2 1 | 2 1 | ||
True | True | ||
</PRE> | |||
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 | 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 | happening, it is useful to draw a state diagram. During the first | ||
iteration, the frame for | iteration, the frame for <CODE>is_reverse</CODE> looks like this: | ||
and adding dotted lines to show that the values of | |||
<DIV CLASS="center"><IMG SRC="book012.png"></DIV> | |||
I took a little license by arranging the variables in the frame | |||
and adding dotted lines to show that the values of <TT>i</TT> and | |||
<TT>j</TT> indicate characters in <TT>word1</TT> and <TT>word2</TT>. | |||
<DIV CLASS="theorem">'''Exercise 8'''  '' | |||
'''' | |||
Starting with this diagram, execute the program on paper, changing the | Starting with this diagram, execute the program on paper, changing the | ||
values of | values of ''''<TT>i</TT>'''' and ''''<TT>j</TT>'''' during each iteration. Find and fix the | ||
second error in this function. | second error in this function. | ||
''</DIV>=== 8.12  Glossary === | |||
<DL CLASS="description"><DT CLASS="dt-description">'''object:'''</DT><DD CLASS="dd-description"> Something a variable can refer to. For now, | |||
you can use “object” and “value” interchangeably. | you can use “object” and “value” interchangeably. | ||
</DD><DT CLASS="dt-description">'''sequence:'''</DT><DD CLASS="dd-description"> An ordered set; that is, a set of | |||
values where each value is identified by an integer index. | values where each value is identified by an integer index. | ||
</DD><DT CLASS="dt-description">'''item:'''</DT><DD CLASS="dd-description"> One of the values in a sequence. | |||
</DD><DT CLASS="dt-description">'''index:'''</DT><DD CLASS="dd-description"> An integer value used to select an item in | |||
a sequence, such as a character in a string. | a sequence, such as a character in a string. | ||
</DD><DT CLASS="dt-description">'''slice:'''</DT><DD CLASS="dd-description"> A part of a string specified by a range of indices. | |||
</DD><DT CLASS="dt-description">'''empty string:'''</DT><DD CLASS="dd-description"> A string with no characters and length 0, represented | |||
by two quotation marks. | by two quotation marks. | ||
</DD><DT CLASS="dt-description">'''immutable:'''</DT><DD CLASS="dd-description"> The property of a sequence whose items cannot | |||
be assigned. | be assigned. | ||
</DD><DT CLASS="dt-description">'''traverse:'''</DT><DD CLASS="dd-description"> To iterate through the items in a sequence, | |||
performing a similar operation on each. | performing a similar operation on each. | ||
</DD><DT CLASS="dt-description">'''search:'''</DT><DD CLASS="dd-description"> A pattern of traversal that stops | |||
when it finds what it is looking for. | when it finds what it is looking for. | ||
</DD><DT CLASS="dt-description">'''counter:'''</DT><DD CLASS="dd-description"> A variable used to count something, usually initialized | |||
to zero and then incremented. | to zero and then incremented. | ||
</DD><DT CLASS="dt-description">'''method:'''</DT><DD CLASS="dd-description"> A function that is associated with an object and called | |||
using dot notation. | using dot notation. | ||
</DD><DT CLASS="dt-description">'''invocation:'''</DT><DD CLASS="dd-description"> A statement that calls a method. | |||
</DD></DL>=== 8.13  Exercises === | |||
<DIV CLASS="theorem">'''Exercise 9'''   | |||
'' | |||
'''' | |||
'' | |||
''A string slice can take a third index that specifies the “step | |||
size;” that is, the number of spaces between successive characters. | size;” that is, the number of spaces between successive characters. | ||
A step size of 2 means every other character; 3 means every third, | A step size of 2 means every other character; 3 means every third, | ||
etc. | etc.'' | ||
<PRE CLASS="verbatim">''>>> fruit = 'banana' | |||
>>> fruit[0:5:2] | >>> fruit[0:5:2] | ||
'bnn' | 'bnn' | ||
''</PRE> | |||
the slice | ''A step size of -1 goes through the word backwards, so | ||
from Exercise  | the slice ''<CODE>''[::-1]''</CODE>'' generates a reversed string.'' | ||
''Use this idiom to write a one-line version of ''<CODE>''is_palindrome''</CODE>'' | |||
from Exercise ''''6.6''''. | |||
'' | |||
</DIV><DIV CLASS="theorem">'''Exercise 10'''  '' | |||
'''' | |||
'' | |||
''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 | might want to experiment with some of them to make sure | ||
you understand how they work. | you understand how they work. ''''<TT>strip</TT>'''' and | ||
''''<TT>replace</TT>'''' are particularly useful.'' | |||
For example, in | |||
indicate optional arguments. So | ''The documentation uses a syntax that might be confusing. | ||
For example, in ''<CODE>''find(sub[, start[, end]])''</CODE>'', the brackets | |||
then | indicate optional arguments. So ''''<TT>sub</TT>'''' is required, but | ||
''''<TT>start</TT>'''' is optional, and if you include ''''<TT>start</TT>'''', | |||
The following functions are all | then ''''<TT>end</TT>'''' is optional. | ||
'' | |||
</DIV><DIV CLASS="theorem">'''Exercise 11'''  '' | |||
The following functions are all ''intended'' to check whether a | |||
string contains any lowercase letters, but at least some of them are | string contains any lowercase letters, but at least some of them are | ||
wrong. For each function, describe what the function actually does. | wrong. For each function, describe what the function actually does.''<PRE CLASS="verbatim">''def any_lowercase1(s): | ||
for c in s: | for c in s: | ||
if c.islower(): | if c.islower(): | ||
| Line 422: | Line 630: | ||
return False | return False | ||
return True | return True | ||
''</PRE></DIV><DIV CLASS="theorem">'''Exercise 12'''  '' | |||
'''' | |||
'' | |||
'' | |||
ROT13 is a weak form of encryption that involves “rotating” each | ROT13 is a weak form of encryption that involves “rotating” each | ||
letter in a word by 13 places | letter in a word by 13 places''<SUP>''1''</SUP>''. To rotate a letter means | ||
to shift it through the alphabet, wrapping around to the beginning if | to shift it through the alphabet, wrapping around to the beginning if | ||
necessary, so ’A’ shifted by 3 is ’D’ and ’Z’ shifted by 1 is ’A’. | necessary, so ’A’ shifted by 3 is ’D’ and ’Z’ shifted by 1 is ’A’.'' | ||
''Write a function called ''<CODE>''rotate_word''</CODE>'' | |||
that takes a string and an integer as parameters, and that returns | that takes a string and an integer as parameters, and that returns | ||
a new string that contains the letters from the original string | a new string that contains the letters from the original string | ||
“rotated” by the given amount. | “rotated” by the given amount. '' | ||
by -10 is “cubed”. | |||
a character to a numeric code, and | ''For example, “cheer” rotated by 7 is “jolly” and “melon” rotated | ||
codes to characters. | by -10 is “cubed”. '' | ||
''You might want to use the built-in functions ''''<TT>ord</TT>'''', which converts | |||
a character to a numeric code, and ''''<TT>chr</TT>'''', which converts numeric | |||
codes to characters.'' | |||
''Potentially offensive jokes on the Internet are sometimes encoded | |||
in ROT13. If you are not easily offended, find and decode some | in ROT13. If you are not easily offended, find and decode some | ||
of them. | of them. | ||
'' | |||
</DIV><HR CLASS="footnoterule"><DL CLASS="thefootnotes"><DT CLASS="dt-thefootnotes"> | |||
1</DT><DD CLASS="dd-thefootnotes">See | |||
<TT>wikipedia.org/wiki/ROT13</TT> | <TT>wikipedia.org/wiki/ROT13</TT> | ||
</DD></DL> | |||
<HR> | <HR> | ||
<IMG SRC="previous_motif.gif" ALT="Previous"> | |||
<IMG SRC="contents_motif.gif" ALT="Up"> | |||
<IMG SRC="next_motif.gif" ALT="Next"> | |||
Revision as of 23:09, 15 September 2008
Chapter 8 Strings
8.1 A string is a sequence
A string is a sequence of characters. You can access the characters one at a time with the bracket operator:
>>> fruit = 'banana' >>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter.
The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name).
But you might not get what you expect:
>>> print letter a
For most people, the first letter of 'banana' is b, not
a. But for computer scientists, the index is an offset from the
beginning of the string, and the offset of the first letter is zero.
>>> letter = fruit[0] >>> print letter b
So b is the 0th letter (“zero-eth”) of 'banana', a
is the 1th letter (“one-eth”), and n is the 2th (“two-eth”)
letter.
You can use any expression, including variables and operators, as an
index, but the value of the index has to be an integer. Otherwise you
get:
>>> letter = fruit[1.5] TypeError: string indices must be integers
=== 8.2 len ===
len is a built-in function that returns the number of characters
in a string:
>>> fruit = 'banana' >>> len(fruit) 6
To get the last letter of a string, you might be tempted to try something like this:
>>> length = len(fruit) >>> last = fruit[length] IndexError: string index out of range
The reason for the IndexError is that there is no letter in ’banana’ 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 length:
>>> last = fruit[length-1] >>> print last a
Alternatively, you can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.
8.3 Traversal with a for loop
A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. One way to write a traversal is with a while loop:
index = 0
while index < len(fruit):
letter = fruit[index]
print letter
index = index + 1
This loop traverses the string and displays each letter on a line by itself. The loop condition is index < len(fruit), so when index 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 len(fruit)-1, which is the last character in the string.
Write a function that takes a string as an argument and displays the letters backward, one per line.
Another way to write a traversal is with a for loop:
for char in fruit:
print char
Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until no characters are left.
The following example shows how to use concatenation (string addition) and a for loop to generate an abecedarian series (that is, in alphabetical order). In Robert McCloskey’s book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order:
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
print letter + suffix
The output is:
Jack Kack Lack Mack Nack Oack Pack Qack
Of course, that’s not quite right because “Ouack” and “Quack” are misspelled.
Modify the program to fix this error.
=== 8.4 String slices ===
A segment of a string is called a slice. Selecting a slice is
similar to selecting a character:
>>> s = 'Monty Python' >>> print s[0:5] Monty >>> print s[6:13] Python
The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. This behavior is counterintuitive, but it might help to imagine the indices pointing between the characters, as in the following diagram:
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:
>>> fruit = 'banana' >>> fruit[:3] 'ban' >>> fruit[3:] 'ana'
If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:
>>> fruit = 'banana' >>> fruit[3:3] ''
An empty string contains no characters and has length 0, but other than that, it is the same as any other string.
Given that 'fruit' is a string, what does 'fruit[:]' mean?
=== 8.5 Strings are immutable ===
It is tempting to use the [] operator on the left side of an
assignment, with the intention of changing a character in a string.
For example:
>>> greeting = 'Hello, world!' >>> greeting[0] = 'J' TypeError: object does not support item assignment
The “object” in this case is the string and the “item” is the character you tried to assign. For now, an object is the same thing as a value, but we will refine that definition later. An item is one of the values in a sequence.
The reason for the error is that
strings are immutable, which means you can’t change an
existing string. The best you can do is create a new string
that is a variation on the original:
>>> greeting = 'Hello, world!' >>> new_greeting = 'J' + greeting[1:] >>> print new_greeting Jello, world!
This example concatenates a new first letter onto a slice of greeting. It has no effect on the original string.
8.6 Searching
What does the following function do?
def find(word, letter):
index = 0
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
In a sense, find is the opposite of the [] operator. Instead of taking an index and extracting the corresponding character, it takes a character and finds the index where that character appears. If the character is not found, the function returns -1.
This is the first example we have seen of a return statement inside a loop. If word[index] == letter, the function breaks out of the loop and returns immediately.
If the character doesn’t appear in the string, the program exits the loop normally and returns -1.
This pattern of computation—traversing a sequence and returning when we find what we are looking for—is a called a search.
Modify 'find' so that it has a third parameter, the index in 'word' where it should start looking.
=== 8.7 Looping and counting ===
The following program counts the number of times the letter a appears in a string:
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print count
This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result—the total number of a’s.
Encapsulate this code in a function named 'count', and generalize it so that it accepts the string and the letter as arguments.
Rewrite this function so that instead of traversing the string, it uses the three-parameter version of 'find' from the previous section.
=== 8.8 string methods ===
A method is similar to a function—it takes arguments and returns a value—but the syntax is different. For example, the method upper takes a string and returns a new string with all uppercase letters:
Instead of the function syntax upper(word), it uses
the method syntax word.upper().
>>> word = 'banana' >>> new_word = word.upper() >>> print new_word BANANA
This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicate that this method takes no argument.
A method call is called an invocation; in this case, we would say that we are invoking upper on the word.
As it turns out, there is a string method named find that is remarkably similar to the function we wrote:
>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1
In this example, we invoke find on word and pass the letter we are looking for as a parameter.
Actually, the find method is more general than our function; it can find substrings, not just characters:
>>> word.find('na')
2
It can take as a second argument the index where it should start:
>>> word.find('na', 3)
4
And as a third argument the index where it should stop:
>>> name = 'bob'
>>> name.find('b', 1, 2)
-1
This search fails because b does not appear in the index range from 1 to 2 (not including 2).
'
There is a string method called 'count' that is similar
to the function in the previous exercise. Read the documentation
of this method
and write an invocation that counts the number of 'a's
in banana.
=== 8.9 The in operator ===
The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second:
>>> 'a' in 'banana' True >>> 'seed' in 'banana' False
For example, the following function prints all the letters from word1 that also appear in word2:
def in_both(word1, word2):
for letter in word1:
if letter in word2:
print letter
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.”
Here’s what you get if you compare apples and oranges:
>>> in_both('apples', 'oranges')
a
e
s
=== 8.10 String comparison ===
The comparison operators work on strings. To see if two strings are equal:
if word == 'banana':
print 'All right, bananas.'
Other comparison operations are useful for putting words in alphabetical order:
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.'
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:
Your word, Pineapple, comes before banana.
A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple.
8.11 Debugging
When you use indices to traverse the values in a sequence, it is tricky to get the beginning and end of the traversal right. Here is a function that is supposed to compare two words and return True if one of the words is the reverse of the other, but it contains two errors:
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
The first if statement checks whether the words are the same length. If not, we can return False immediately and then, for the rest of the function, we can assume that the words are the same length. This is an example of the guardian pattern in Section 6.8.
i and j are indices: i traverses word1 forward while j traverses word2 backward. If we find two letters that don’t match, we can return False immediately. If we get through the whole loop and all the letters match, we return True.
If we test this function with the words “pots” and “stop”, we expect the return value True, but we get an IndexError:
>>> is_reverse('pots', 'stop')
...
File "reverse.py", line 15, in is_reverse
if word1[i] != word2[j]:
IndexError: string index out of range
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.
while j > 0:
print i, j # print here
if word1[i] != word2[j]:
return False
i = i+1
j = j-1
Now when I run the program again, I get more information:
>>> is_reverse('pots', 'stop')
0 4
...
IndexError: string index out of range
The first time through the loop, the value of j is 4,
which is out of range for the string 'pots'.
The index of the last character is 3, so the
initial value for j should be len(word2)-1.
If I fix that error and run the program again, I get:
>>> is_reverse('pots', 'stop')
0 3
1 2
2 1
True
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 is_reverse looks like this:
I took a little license by arranging the variables in the frame and adding dotted lines to show that the values of i and j indicate characters in word1 and word2.
' Starting with this diagram, execute the program on paper, changing the values of 'i' and 'j' during each iteration. Find and fix the second error in this function.
=== 8.12 Glossary ===
- object:
- Something a variable can refer to. For now, you can use “object” and “value” interchangeably.
- sequence:
- An ordered set; that is, a set of values where each value is identified by an integer index.
- item:
- One of the values in a sequence.
- index:
- An integer value used to select an item in a sequence, such as a character in a string.
- slice:
- A part of a string specified by a range of indices.
- empty string:
- A string with no characters and length 0, represented by two quotation marks.
- immutable:
- The property of a sequence whose items cannot be assigned.
- traverse:
- To iterate through the items in a sequence, performing a similar operation on each.
- search:
- A pattern of traversal that stops when it finds what it is looking for.
- counter:
- A variable used to count something, usually initialized to zero and then incremented.
- method:
- A function that is associated with an object and called using dot notation.
- invocation:
- A statement that calls a method.
=== 8.13 Exercises ===
'
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.
''>>> fruit = 'banana' >>> fruit[0:5:2] 'bnn' ''
A step size of -1 goes through the word backwards, so
the slice [::-1] generates a reversed string.
Use this idiom to write a one-line version of is_palindrome
from Exercise '6.6'.
' Read the documentation of the string methods at 'docs.python.org/lib/string-methods.html'. You might want to experiment with some of them to make sure you understand how they work. 'strip' and 'replace' are particularly useful.
The documentation uses a syntax that might be confusing.
For example, in find(sub[, start[, end]]), the brackets
indicate optional arguments. So 'sub' is required, but
'start' is optional, and if you include 'start',
then 'end' is optional.
The following functions are all intended to check whether a string contains any lowercase letters, but at least some of them are
wrong. For each function, describe what the function actually does.''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
''' ROT13 is a weak form of encryption that involves “rotating” each letter in a word by 13 places1. To rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary, so ’A’ shifted by 3 is ’D’ and ’Z’ shifted by 1 is ’A’.
Write a function called rotate_word
that takes a string and an integer as parameters, and that returns
a new string that contains the letters from the original string
“rotated” by the given amount.
For example, “cheer” rotated by 7 is “jolly” and “melon” rotated by -10 is “cubed”.
You might want to use the built-in functions 'ord', which converts a character to a numeric code, and 'chr', which converts numeric codes to characters.
Potentially offensive jokes on the Internet are sometimes encoded in ROT13. If you are not easily offended, find and decode some of them.
- 1
- See wikipedia.org/wiki/ROT13
<IMG SRC="previous_motif.gif" ALT="Previous"> <IMG SRC="contents_motif.gif" ALT="Up"> <IMG SRC="next_motif.gif" ALT="Next">