This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: Object methods

String methods

face Josiah Wang Oana Cocarascu

Python objects usually come with methods.

For example, str has many convenient methods that you can use.

Let’s get you exploring the methods for str with a quiz!

You might want to have the official documentation for str ready. The answers can all be found on the page!

1 2 3 4 5 6 7 8 9 10 11 12 13 14

Question 1

Given name = "gordon ramsay", write a method call to automatically check whether name ends with an "a" (hint: the answer can be found in the previous page!)

name.endswith("a")
Explanation:

The answer should be quite self-explanatory. The str object has methods str.startswith() and str.endswith(), and the input argument does not have to be a single character. For example, you can also call name.endswith("say") which returns True for name = "gordon ramsay".

Question 2

Given name = "gordon ramsay", write a method call to automatically convert name to all uppercase (i.e. "GORDON RAMSAY") and return this uppercased string.

name.upper()
Explanation:

The method call str.upper() returns a new string that converts the string referred to by name to uppercase. To convert a string to lowercase, use str.lower().

Question 3

Given name = "gordon ramsay", write a method call to automatically convert name so that the first letter in each word in the string starts with a capital letter (i.e. "Gordon Ramsay"). The method call should return this converted string.

name.title()
Explanation:

The method str.title() returns a new string in title case. Note that this is different from name.capitalize() that capitalizes only the very first letter of the whole string.

Question 4

Given name = "gordon ramsay", write a method call to automatically check whether all characters in name are lowercase. In this example, the method call should return True.

name.islower()
Explanation:

The method str.islower() checks whether a string is made up of entirely lowercase letters. Also check out str.isupper() and str.istitle().

Question 5

Given word = "hello 123!", write a method call that automatically checks whether word is made up of only uppercase letters, lowercase letters and digits. In this example, it should return False because word contains a space and also an exclamation mark. It should return True if word = "hello123".

word.isalnum()
Explanation:

The method str.isalnum() checks whether a string is made up of entirely alphanumeric characters. Also check out str.isalpha(), str.isdigit(), str.isnumeric(), and str.isspace().

Question 6

Given sentence = "one little two little three little indians", write a method call that automatically returns a new string which replaces all occurrences of "little" in sentence with "big", i.e. "one big two big three big indians"

sentence.replace("little", "big")
Explanation:

The method str.replace(original, new) can be used to replace a substring in str with another substring. There is a third optional parameter that limits the number of replacements done (see documentation for details).

Question 7

You are given the two variables below.

sentence = "the cat is on the mat"
query = "at"

Write a method call that searches sentence for the query and returns the index of the first occurrence of query in sentence. The expected return value for the following example is 5.

sentence.find(query)
Explanation:

There are two possible answers for this question: sentence.find(query) and sentence.index(query). What is the difference between the two? Find out from the documentation! 😉 The documentation also describes a few more optional arguments.

Question 8

What is the output of the following piece of code?

count = "£100 £200 £300".count("£")
print(count)
3
Explanation:

The str.count(substring) method counts the number of times a substring occurs in the str.

Question 9

What is the output of the following piece of code?

count = "£100 £200 £300".count("£", 5, 10)
print(count)
1
Explanation:

The str.count() method has two optional arguments (start index and end index) that limit the search to the specified slice of the string. It only counts the occurrences of a substring within the specified slice. In this case, only the £ in £200 is counted.

Question 10

What is the output of the following piece of code?

numbers = "1,2,5".split(",")
print(numbers)
["1", "2", "5"]
Explanation:

This piece of code splits the string "1,2,5" by the given separator (","). Note that the output is a list of strings, so you will have to convert the strings to integers if you need them as integers.

If you do not provide a separator, then the method will split by whitespace (spaces, newlines, tabs, etc.). So "1 2 5".split() will result in ["1", "2", "5"].

Question 11

Given digits = ["1", "2", "5"], write a method call that joins the strings in the list digits, separated by commas, and returns the joined string as a str i.,e. "1,2,5".

",".join(digits)
Explanation:

You might have thought that it would be digits.join(","), but it is actually ",".join(digits), where "," is the 'connector string'. .join() is a str method, not a list method. This was Python's design decision so that you can join any other sequence types and not just lists. A bit counter-intuitive, but you will get used to it!

Question 12

What is the output after executing the following code?

line = "  pen pineapple apple pen \n   "
things = line.strip()
print(things)
pen pineapple apple pen
Explanation:

The method line.strip() returns a copy of line, removing any whitespace (spaces, newlines etc.) from the beginning and the end of line. The result is "pen pineapple apple pen". Especially useful when you are reading from a text file which might contain new lines. Use str.lstrip() if you only want to remove whitespaces from the beginning of a string ("left strip"), and str.rstrip() to remove them from the end of a string ("right strip").

Question 13

What is the value of things after executing the following code?

line = "  pen pineapple apple pen \n   "
things = line.strip().split()
["pen", "pineapple", "apple", "pen"]
Explanation:

One advantage of using methods is that you can chain methods to perform multiple actions in a single line.

In this example, you can interpret the expression as (line.strip()).split(). line.strip() returns a copy of line, removing any whitespace (spaces, newlines etc.) from the beginning and end of line. The result is "pen pineapple apple pen", to which you apply "pen pineapple apple pen".split(), which splits the string by whitespace and returns a list containing each of the words.

Contrast this chaining approach to function composition i.e. split(strip(line)). The approach using methods might be easier to read (left to right), rather than from 'inside' to 'outside'.

Question 14

What is the output after executing the following code?

host = "www.example.com".strip('cmowz.')
print(host)
example
Explanation:

You can also remove a SET of characters from the beginning and end of a string with str.strip() if you specify them as an input argument. In this example, the method keeps removing a character from the beginning and the end of a string if it matches any of the specified characters, and stops once it does not match. At the beginning of the string, "www." is removed, and stops at "e" since it is not specified as one of the characters. Similarly, ".com" is removed at the end of the str.