CodeMIRAI
0 XP

String methods

2 min read 7 runnable examples Quiz included

A method is a function that belongs to a value. You call it with a dot: text.upper(). Strings have dozens of methods; these are the ones you will use constantly. Remember that every one of them returns a new string and leaves the original alone.

Changing case

Python
title = "the lord of the rings"
print(title.upper())
print(title.lower())
print(title.title())
print(title.capitalize())
print("Hello".swapcase())

Cleaning up whitespace

Text typed by people often has stray spaces. strip() removes them from both ends:

Python
raw = "   asha@example.com  \n"
print(repr(raw))
print(repr(raw.strip()))
print(repr(raw.lstrip()))     # left only
print(repr(raw.rstrip()))     # right only
print("xxhixx".strip("x"))    # strip chosen characters

repr() shows the string with its quotes and hidden characters, which makes spaces visible.

Searching

Python
sentence = "Practice makes progress, practice makes perfect"
print(sentence.count("makes"))
print(sentence.find("progress"))     # index of first match
print(sentence.find("failure"))      # -1 means "not found"
print(sentence.startswith("Practice"))
print(sentence.endswith("perfect"))

find() returns -1 when there is no match; index() does the same job but raises an error instead.

Replacing

Python
text = "I like cats. Cats are great."
print(text.replace("cats", "dogs"))
print(text.replace("a", "@", 2))     # only the first 2

Splitting and joining

split() breaks a string into a list; join() glues a list back together.

Python
csv_line = "Asha,21,Mumbai"
fields = csv_line.split(",")
print(fields)

words = "  many   spaces   here ".split()   # no argument: split on any whitespace
print(words)

print("-".join(["2026", "10", "29"]))
print(" ".join(words))

Checking content

Python
print("12345".isdigit())
print("abc".isalpha())
print("abc123".isalnum())
print("   ".isspace())
print("Hello".isupper(), "HELLO".isupper())

These are handy for validating input before you convert it.

Chaining methods

Because each method returns a string, you can call one after another:

Python
messy = "   HeLLo WoRLD   "
print(messy.strip().lower().replace("world", "Python"))
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.