Python String Methods
In this page:
string.method_name(arguments)
# e.g. string.upper(), string.replace(old, new)
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()) # "yes"
print(text.upper()) # "YES"
print(text.title()) # "Yes"
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()) # removes whitespace from both ends
print(text.lstrip()) # removes whitespace from the left only
print(text.rstrip()) # removes whitespace from the right only
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(",") # breaks the string into a list wherever a comma appears
print(words)
print("-".join(words)) # stitches the list back into a string, separated by "-"
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")) # index of the first occurrence of "na"
print(text.count("a")) # how many times "a" appears
- Calling
s.upper()ors.strip()and ignoring the result, when string methods return a new string and leavesunchanged (s = s.strip()). - Using
s.find("x")in anifas if it returned a boolean, so a match at index 0 is falsy and-1(not found) is truthy. - Expecting
split()to return a string, when it returns a list, so"a,b".split(",")[0]is needed to get one piece.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: