Going Deeper with Strings

Read this for more on strings.

8. String methods

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().

>>> word = 'banana'
>>> new_word = word.upper()
>>> new_word

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:
>>> word = 'banana'
>>> index = word.find('a')
>>> index

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')

By default, find starts at the beginning of the string, but it can take a second argument, the index where it should start:
>>> word.find('na', 3)
This is an example of an optional argument; find can also take a third argument, the index where it should stop:
>>> name = 'bob'
>>> name.find('b', 1, 2)
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.