Lesson 32/48 ยท ๐ฆ Data Structures
๐ฆ Data StructuresLesson 32/48
Phase 5 ยท Data Structures20 min
String Methods
len, upper, lower, split, join, replace, the toolkit for text
Strings have built-in methods, actions you can call on them using dot notation. You've already used
print(); now meet the toolkit for text manipulation.Calling a method with dot notationpython
name = "alice"
print(name.upper()) # ALICE
print(name.lower()) # alice, original is unchanged
print(len(name)) # 5 (len is a function, not a method)Methods don't change the original string, they return a new one. Strings in Python are *immutable*.
The most useful string methods
s.upper() / s.lower(), change cases.strip(), remove leading/trailing whitespace (great for cleaning user input)s.replace(old, new), swap one substring for anothers.split(sep), split into a list of partssep.join(list), join a list back into a strings.startswith(x) / s.endswith(x), boolean checksstrip and replacepython
raw = " Hello, World! "
clean = raw.strip()
print(clean) # Hello, World!
print(clean.replace("World", "Python")) # Hello, Python!๐คQuick Check
What does "hello".upper() return?
split and join, a power duopython
sentence = "one,two,three"
words = sentence.split(",") # ["one", "two", "three"]
print(words[1]) # two
rejoined = " - ".join(words) # "one - two - three"
print(rejoined)split() with no argument splits on any whitespace (spaces, tabs, newlines) and removes the empty strings, handy for tokenising sentences.The `in` operator, check if a substring exists
You already know
You already know
in for loops. With strings it tests membership:in operator for stringspython
email = "alice@example.com"
if "@" in email:
print("Looks like a valid email")
print("@" in email) # True
print("xyz" in email) # False๐คQuick Check
What does "apple,banana,cherry".split(",") produce?
Practice Exercises
0/3 solvedExercise 1 of 3easy
โฑ 00:00Name Formatter
Write a program that takes a name with messy casing and extra spaces and prints it in "Title Case" with no leading/trailing whitespace.
Input (already in the code):
Hint: chain .strip() then .title()
Input (already in the code):
" alice SMITH "Expected output: Alice SmithHint: chain .strip() then .title()
solution.py
1 / 3
Exercise 2 of 3easy
โฑ 00:00CSV Row Parser
You receive a line from a CSV file:
Split it into parts and print:- Name: Alice- Age: 30- City: London
"Alice,30,London"Split it into parts and print:- Name: Alice- Age: 30- City: London
solution.py
2 / 3
Exercise 3 of 3medium
โฑ 00:00Censor Filter
Replace every occurrence of the word
Message:
Print the cleaned message, then print True or False for whether "bad" is still in it.
"bad" in a message with "***", then check if the cleaned message still contains "bad".Message:
"This is bad and really bad behaviour"Print the cleaned message, then print True or False for whether "bad" is still in it.
solution.py
3 / 3
Solve all 3 exercises to unlock completion