Python String Methods
String methods are built-in functions that transform, search, and inspect text.
Calling a Method
A method is a function that belongs to an object. You call a string method by writing the string, a dot, the method name, and a pair of parentheses. Because strings are immutable, these methods never change the original value; they return a new string that you usually assign to a variable or print.
Changing case
title = "the art of code"
print(title.upper())
print(title.title())
print(title.capitalize())
print(title)Notice that the last line still prints the original lowercase text. The methods produced new strings without touching the variable they were called on.
Cleaning and Searching
- strip() removes leading and trailing whitespace, which is useful for tidying user input.
- replace(old, new) swaps every occurrence of one substring for another.
- find(sub) returns the index of the first match, or -1 when nothing is found.
- count(sub) reports how many times a substring appears.
- startswith(sub) and endswith(sub) return True or False for a prefix or suffix check.
Cleaning input
raw = " user@example.com "
clean = raw.strip()
print(clean)
print(clean.replace("example", "mail"))
print(clean.endswith(".com"))
print(clean.find("@"))Splitting and Joining
split() breaks a string into a list of smaller strings using a separator you choose, while join() does the reverse by stitching a list of strings back together with a separator between each item. Together they are the backbone of simple text processing.
Split and join
csv = "apple,banana,cherry"
fruits = csv.split(",")
print(fruits)
joined = " | ".join(fruits)
print(joined)