Skip to main content

Section 3.8 String Methods

We previously used a few functions like print() and len() where we place the variable inside the parentheses such as len(my_str). On the other hand, a method is a function that is attached to a specific Python object. To access this function, we write the object, then a dot ., and then the name of the method. The "dot notation" is the way we connect the name of an object to the name of a method it can perform. For example, we can write my_str.upper() when we want the string my_str to perform the upper() method to create an upper-case version of itself.
Remember that strings are immutable. Therefore, all string methods give us a new string and must be assigned to a new variable. The original string is unchanged.
In this example, upper is a method that can be invoked on any string object to create a new string in which all the characters are in uppercase.
In addition to upper, the following table provides some useful string methods.
Table 3.8.1.
Method Parameters Description
upper none Returns a string in all uppercase
lower none Returns a string in all lowercase
count item Returns the number of occurrences of item
replace old, new Replaces all occurrences of old substring with new
index item Returns the leftmost index where the substring item is found, or error if not found
You should experiment with these methods so that you understand what they do. Note once again that the methods that return strings do not change the original.
Check your understanding

Checkpoint 3.8.2.

    What is printed by the following statements?
    s = "python rocks"
    print(s.count("o") + s.count("p"))
    
  • 0
  • There are definitely o and p characters.
  • 2
  • There are 2 o characters but what about p?
  • 3
  • Yes, add the number of o characters and the number of p characters.

Checkpoint 3.8.3.

    What is printed by the following statements?
    s = "python rocks"
    print(s[1] * s.index("n"))
    
  • yyyyy
  • Yes, s[1] is y and the index of n is 5, so 5 y characters. It is important to realize that the index method has precedence over the repetition operator.
  • 55555
  • Close. 5 is not repeated, it is the number of times to repeat.
  • n
  • This expression uses the index of n
  • Error, you cannot combine all those things together.
  • This is fine, the repetition operator used the result of indexing and the index method.
You have attempted of activities on this page.