21.8: String Methods
- Page ID
- 16991
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
).
Exercise \(\PageIndex{1}\)
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'
.
Exercise \(\PageIndex{2}\)
Read the documentation of the string methods at http://docs.python.org/2/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.