Python String Methods
In this page:
Case Conversions
.lower(), .upper(), and .title() return a new string with adjusted letter casing — commonly used to normalize user input for comparison, since "Yes" and "yes" would otherwise be treated as different strings.
Example: Case Conversions
text = "Yes"
print(text.lower())
print(text.upper())
print(text.title())
Stripping Whitespace
.strip() removes leading and trailing whitespace from a string, while .lstrip() and .rstrip() trim only the left or right side respectively — essential for cleaning up text pasted or typed by a user that might carry stray spaces.
Example: Stripping Whitespace
text = " hello "
print(text.strip())
print(text.lstrip())
print(text.rstrip())
Replacing Substrings
.replace(old, new) scans a string for every occurrence of old and swaps it for new, returning the modified copy — useful for tasks like sanitizing input or performing simple find-and-replace text transformations.
Example: Replacing Substrings
text = "I like cats"
print(text.replace("cats", "dogs"))
Splitting and Joining
.split() breaks a string into a list of substrings wherever a separator occurs (whitespace by default), and .join() does the reverse, stitching a list of strings back together using a chosen separator between each piece.
Example: Splitting and Joining
words = "a,b,c".split(",")
print(words)
print("-".join(words))
Finding and Counting
.find() searches for a substring and returns the index of its first occurrence (or -1 if it's not present), while .count() instead returns how many times that substring appears anywhere in the string.
Example: Finding and Counting
text = "banana"
print(text.find("na"))
print(text.count("a"))
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: