MethodsΒΆ

The majority of the functions we will encounter when working with strings are methods. The difference between a method and other types of functions we will encounter is subtle, and will be discussed in greater detail later in the course. For now, we simply note the following points regarding methods:

  1. A method is a function that belongs to a specific object (such as an int, float, or str).

  2. To use a method on an object, you write the name of the object, followed by a dot, followed by the name of the method, followed by a set of parentheses.

In the following example, we consider three string methods:

  • upper() converts the string to uppercase.

  • lower() converts the string to lowercase.

  • title() capitalizes the first letter of each word in the string.

Note that none of these methods actually change the contents of the string. They instead provide a new string as their output.

myString = "There's a method in the madness."
print(myString.upper())
print(myString.lower())
print(myString.title())
THERE'S A METHOD IN THE MADNESS.
there's a method in the madness.
There'S A Method In The Madness.

Some methods accept inputs (also called arguments). One example is the count() method. This method searches the string to see how many times the supplied input (also a string) appears within the original string. This is demonstrated below.

print( myString.count("m") )
print( myString.count("e") )
2
5

The replace() method accepts two arguments. This method scans the source string, and replaces all occurences of the first argument with the second argument. Again, it does not actually change the contents of the original string. It instead returns a new string as output.

a = "a "
b =  "no "
print( myString.replace(a, b) )
There's no method in the madness.