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

python
text = "  Hello, Chennai!  "
print(text.strip())
print(text.strip().upper())
print(text.strip().lower())
print(text.strip().replace("Chennai", "Madurai"))
print("tamil nadu".title())
Output
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

python
line = "idli,dosa,vada"
items = line.split(",")
print(items)
print(" | ".join(items))
print("one two  three".split())
Output
['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

python
email = "priya@example.com"
print(email.find("@"))
print(email.count("e"))
print(email.startswith("priya"))
print(email.endswith(".in"))
print("2024".isdigit(), "20a4".isdigit())
Output
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.

python
name = "ravi"
name.upper()
print(name)
name = name.upper()
print(name)
Output
ravi
RAVI

What does "-".join(["a", "b", "c"]) give?

Try this now

  1. Ask for a full name and print the initials in capitals, such as "K.R.".
  2. Count how many times the letter "a" appears in a sentence, ignoring case.
  3. 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.