String Methods

Strings come with over forty built-in methods. This lesson groups the most useful ones by job — changing case, cleaning whitespace, searching, replacing, splitting and testing — so you know where to look when you need one.

Changing case

PY case.py
s = "hello wORLD"

print(s.upper())
print(s.lower())
print(s.title())
print(s.capitalize())
print(s.swapcase())
print("Straße".casefold())
Output
HELLO WORLD
hello world
Hello World
Hello world
HELLO World
strasse

casefold() is a stronger version of lower() designed for case-insensitive comparisons across languages.

Removing whitespace and characters

PY strip.py
raw = "   padded text \n"

print(repr(raw.strip()))
print(repr(raw.lstrip()))
print(repr(raw.rstrip()))
print("***bold***".strip("*"))
print("report_final.pdf".removesuffix(".pdf"))
print("Mr. Smith".removeprefix("Mr. "))
Output
'padded text'
'padded text \n'
'   padded text'
bold
report_final
Smith

strip() removes any of the given characters from both ends (whitespace by default). To remove an exact prefix or suffix, use removeprefix/removesuffix — strip would remove matching characters one at a time, which is a classic bug.

Searching

PY search.py
s = "the rain in spain"

print(s.find("ain"))
print(s.rfind("ain"))
print(s.find("snow"))
print(s.count("ain"))
print(s.startswith("the"), s.endswith(("ain", "ow")))
print(s.index("rain"))
Output
5
14
-1
2
True True
4

find returns -1 if not found, while index raises a ValueError. startswith and endswith accept a tuple to test several options at once. For a simple yes/no, use the in operator.

Replacing

PY replace.py
s = "one, two, two, three"

print(s.replace("two", "2"))
print(s.replace("two", "2", 1))
print("a-b_c".translate(str.maketrans("-_", "  ")))
Output
one, 2, 2, three
one, 2, two, three
a b c

Splitting and joining

PY split.py
csv_line = "Ana,31,Lisbon"
print(csv_line.split(","))

print("  lots   of   space ".split())
print("a=1=2".split("=", 1))
print("line1\nline2\nline3".splitlines())
print("user@example.com".partition("@"))

print(" | ".join(["red", "green", "blue"]))
Output
['Ana', '31', 'Lisbon']
['lots', 'of', 'space']
['a', '1=2']
['line1', 'line2', 'line3']
('user', '@', 'example.com')
red | green | blue

split() with no argument splits on any run of whitespace and ignores leading/trailing spaces. partition splits once into exactly three parts. join is called on the separator and takes an iterable of strings.

Alignment and padding

PY align.py
for item, price in [("Tea", 3), ("Cake", 4.5), ("Sandwich", 7.25)]:
    print(item.ljust(10, ".") + f"{price:>6.2f}")

print("42".zfill(5))
print("title".center(15, "~"))
Output
Tea.......  3.00
Cake......  4.50
Sandwich..  7.25
00042
~~~~~title~~~~~

Testing content

PY tests.py
print("12345".isdigit(), "12.5".isdigit())
print("Hello".isalpha(), "Hello1".isalnum())
print("   ".isspace(), "Title Case".istitle())
print("ABC".isupper(), "abc".islower())
print("my_var".isidentifier())
Output
True False
True True
True True
True True
True

These are handy for quick validation, but note "12.5".isdigit() is false — to check whether a string is a valid number, try converting it with float() instead.

Chaining methods

PY chain.py
title = "  Hello, World! Welcome to Python.  "

slug = (
    title.strip()
    .lower()
    .replace(",", "")
    .replace("!", "")
    .replace(".", "")
    .replace(" ", "-")
)
print(slug)
Output
hello-world-welcome-to-python

Quick reference

JobMethods
Caseupper lower title capitalize swapcase casefold
Trimstrip lstrip rstrip removeprefix removesuffix
Searchfind rfind index count startswith endswith
Replacereplace translate expandtabs
Split / joinsplit rsplit splitlines partition join
Alignljust rjust center zfill
Testisdigit isalpha isalnum isspace isupper islower

Try it yourself

Try it yourself
Console output