String Methods
A method is an operation you call on a value. Write the value, a dot, the method name and parentheses, as in name.upper(). String methods can change the case of text, replace text or split it into parts.
upper and lower
name = "Sanjin"
print(name.upper())
print(name.lower())
For simple case-insensitive comparisons, lowercasing both strings can make "Red" and "red" match. Only do this when the task asks you to ignore case; some tasks deliberately distinguish uppercase and lowercase.
replace
sentence = "I like cats"
print(sentence.replace("cats", "dogs"))
print(sentence)
Strings cannot be changed in place. Methods such as .upper(), .lower() and .replace() return a string without changing the original. To use the returned text later, save it, for example sentence = sentence.replace("cats", "dogs"). Other string methods can return other types of values.
With two arguments, .replace(old, new) replaces all non-overlapping matches, including matches inside longer words. Matching is case-sensitive. An empty replacement string removes the matching text.
split
With no argument, .split() returns a list of pieces separated by whitespace, such as spaces, tabs or newlines. Repeated whitespace is treated as one separator, and leading or trailing whitespace does not create empty pieces.
line = "red green blue"
words = line.split()
print(words)
print(len(words))
Chaining methods
You can call another method on a result when that result supports the method. Here .lower() returns a string, so .split() can be called on it; .split() then returns a list.
text = "Red RED red"
print(text.lower().split())
text.lower() makes one lowercase string, and .split() turns that into a
list — the standard first step for counting words.
See also: Indexing, String Formatting, Lists.
Your turn
Print the title in capitals, then print it with great replaced by small.
title = "the great escape"
# print the title in capitals, then with "great" replaced by "small" (two lines)
Expected output
THE GREAT ESCAPE
the small escape
Practise this in the free Python course, where every exercise checks your code instantly.