String Methods Examples
Short, runnable programs that show python string methods in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python String Methods lesson.
1Normalising an email address
Emails are case-insensitive and often typed with stray spaces, so clean them before comparing or storing.
typed = " Maya.Rao@Example.COM \n"
email = typed.strip().lower()
print(email)
print(email.endswith("@example.com"))
print(email.split("@")[0])Expected outputmaya.rao@example.com
True
maya.rao
2Splitting a CSV-style line
split() turns one line of text into a list, then each field can be cleaned and converted.
line = "Notebook, 3, 2.50"
item, qty, price = [p.strip() for p in line.split(",")]
total = int(qty) * float(price)
print(item, total)Expected outputNotebook 7.5
3Building a URL slug
Chaining methods turns an article title into a lowercase, dash-separated slug.
title = " Top 5 Python Tricks for Beginners "
slug = "-".join(title.lower().split())
print(slug)Expected outputtop-5-python-tricks-for-beginners
4Counting words and finding a term
split() plus len() counts words; count() and find() search inside text.
review = "Great phone, great battery, poor camera"
print("Words:", len(review.split()))
print("great appears", review.lower().count("great"), "times")
print("camera at index", review.find("camera"))Expected outputWords: 6
great appears 2 times
camera at index 33
5Aligned receipt lines
ljust() and rjust() line up columns in plain text output.
items = [("Tea", 3.5), ("Sandwich", 7.25), ("Cake", 4.0)]
for name, price in items:
print(name.ljust(10, ".") + f"{price:.2f}".rjust(6))Expected outputTea....... 3.50
Sandwich.. 7.25
Cake...... 4.00
6Reading key=value settings with partition
partition() always returns three parts, so unpacking is safe even when the separator is missing.
lines = ["theme = dark", "volume=7", "debug"]
settings = {}
for line in lines:
key, sep, value = line.partition("=")
settings[key.strip()] = value.strip() if sep else "true"
print(settings)Expected output{'theme': 'dark', 'volume': '7', 'debug': 'true'}
Practise next
Python String Methods exercises → Back to the lesson
Python Strings examplesPython f-Strings examplesPython List Methods examplesPython Slicing examples