Strings provide methods that perform a variety of useful operations. A method is similar to a function—it takes arguments and returns a value—but the syntax is different. For example, the method 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().
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 arguments.
A method call is called an invocation; in this case, we would say that we are invoking upper on word.
As it turns out, there is a string method named find that is remarkably similar to the function we wrote:
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:
By default, find starts at the beginning of the string, but it can take a second argument, the index where it should start:
This is an example of an optional argument; find can also take a third argument, the index where it should stop:
This search fails because b does not appear in the index range from 1 to 2, not including 2. Searching up to, but not including, the second index makes find consistent with the slice operator.
The relational operators work on strings. To see if two strings are equal:
Other relational operations are useful for putting words in alphabetical order:
Python does not handle uppercase and lowercase letters the same way people do. All the uppercase letters come before all the lowercase letters, so:
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.
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:
The first if statement checks whether the words are the same length. If not, we can return False immediately. Otherwise, for the rest of the function, we can assume that the words are the same length.
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:
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.
Now when I run the program again, I get more information:
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:
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
is shown in
Figure 16.1.
I took some 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, run the program on paper, changing the values of i and j during each iteration. Find and fix the second error in this function.
Something a variable can refer to. For now, you can use “object” and “value” interchangeably.
An ordered collection of values where each value is identified by an integer index.
One of the values in a sequence.
An integer value used to select an item in a sequence, such as a character in a string. In Python indices start from 0.
A part of a string specified by a range of indices.
A string with no characters and length 0, represented by two quotation marks.
The property of a sequence whose items cannot be changed.
To iterate through the items in a sequence, performing a similar operation on each.
A pattern of traversal that stops when it finds what it is looking for.
A variable used to count something, usually initialized to zero and then incremented.
A statement that calls a method.
A function or method argument that is not required.
Read the documentation of the string methods at http://docs.python.org/3/library/stdtypes.html#string-methods. 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.
There is a string method called count that is similar
to the function in Section 15.3. Read the documentation
of this method
and write an invocation that counts the number of a’s
in ’banana’
.
The following functions are all intended to check whether a string contains any lowercase letters, but at least some of them are wrong. For each function, describe what the function actually does (assuming that the parameter is a string).
A Caesar cypher is a weak form of encryption that involves “rotating” each letter by a fixed number of places. To rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary, so ’A’ rotated by 3 is ’D’ and ’Z’ rotated by 1 is ’A’.
To rotate a word, rotate each letter by the same amount. For example, “cheer” rotated by 7 is “jolly” and “melon” rotated by -10 is “cubed”. In the movie 2001: A Space Odyssey, the ship computer is called HAL, which is IBM rotated by -1.
Write a function called rotate_word
that takes a string and an integer as parameters, and returns
a new string that contains the letters from the original string
rotated by the given amount.
You might want to use the built-in function ord, which converts a character to a numeric code, and chr, which converts numeric codes to characters. Letters of the alphabet are encoded in alphabetical order, so for example:
Because ’c’
is the two-eth letter of the alphabet. But
beware: the numeric codes for upper case letters are different.
Potentially offensive jokes on the Internet are sometimes encoded in ROT13, which is a Caesar cypher with rotation 13. If you are not easily offended, find and decode some of them.