Lesson 5 of 6 · Numbers, Strings and Operators · 3 min read · Updated
String methods
Cleaning, changing, splitting and searching text with the tools built into every string.
A method is a function that belongs to a value. You call it with a dot: name.upper(). Strings come with dozens; these are the ones you will reach for weekly.
Cleaning and changing
text = " Hello, Chennai! "
print(text.strip())
print(text.strip().upper())
print(text.strip().lower())
print(text.strip().replace("Chennai", "Madurai"))
print("tamil nadu".title())
Hello, Chennai!
HELLO, CHENNAI!
hello, chennai!
Hello, Madurai!
Tamil Nadu
Note
strip() removes spaces from both ends. Use it on anything a user types — a stray space is why "yes " == "yes" is False.
Splitting and joining
line = "idli,dosa,vada"
items = line.split(",")
print(items)
print(" | ".join(items))
print("one two three".split())
['idli', 'dosa', 'vada']
idli | dosa | vada
['one', 'two', 'three']
split() breaks a string into a list; with no argument it splits on any run of spaces. join() does the reverse — note that it is called on the separator, with the list inside the brackets.
Searching and testing
email = "priya@example.com"
print(email.find("@"))
print(email.count("e"))
print(email.startswith("priya"))
print(email.endswith(".in"))
print("2024".isdigit(), "20a4".isdigit())
5
2
True
False
True False
find() gives the position of the first match, or -1 if there is none. isdigit() is the quick check before converting input with int().
Warning
Methods give back a new string; the original is untouched. name.upper() on its own line does nothing useful. Write name = name.upper() to keep the result.
name = "ravi"
name.upper()
print(name)
name = name.upper()
print(name)
ravi
RAVI
What does "-".join(["a", "b", "c"]) give?
Try this now
- Ask for a full name and print the initials in capitals, such as "K.R.".
- Count how many times the letter "a" appears in a sentence, ignoring case.
- Ask "Continue? (yes/no)" and accept " YES " as yes by using strip() and lower().
Create a free account to save your progress, or sign in.