String Methods
Because strings are objects, they come with a large set of built-in methods for transforming, searching, and inspecting text. All of these methods return a new string (or other value) rather than modifying the original, since strings are immutable.
Changing Case
text = "Hello, World!" print(text.upper()) # HELLO, WORLD! print(text.lower()) # hello, world! print(text.title()) # Hello, World! print(text.capitalize()) # Hello, world! print(text.swapcase()) # hELLO, wORLD!
Stripping Whitespace
.strip(), .lstrip(), and .rstrip() remove leading/trailing whitespace (or any characters you specify) — extremely common when cleaning up user input or lines read from a file.
raw = " padded text \n"
print(repr(raw.strip())) # 'padded text'
print(repr(raw.lstrip())) # 'padded text \n'
print(repr(raw.rstrip())) # ' padded text'
# strip() can also remove specific characters, not just whitespace
print("***important***".strip("*")) # importantSplitting and Joining
.split() breaks a string into a list of pieces, and .join() does the reverse, stitching a list of strings back together with a given separator.
sentence = "the quick brown fox"
words = sentence.split() # splits on any whitespace by default
print(words) # ['the', 'quick', 'brown', 'fox']
csv_row = "id,name,email"
fields = csv_row.split(",") # split on a specific separator
print(fields) # ['id', 'name', 'email']
rejoined = "-".join(fields)
print(rejoined) # id-name-email
print(" ".join(words)) # the quick brown foxReplacing Text
sentence = "I like cats. Cats are great."
print(sentence.replace("Cats", "Dogs"))
# I like cats. Dogs are great.
# An optional third argument limits how many replacements happen
print("aaaa".replace("a", "b", 2)) # bbaaSearching Inside a String
.find() and .index() both locate the position of a substring, but they differ in how they handle a “not found” result.
text = "learning python is fun"
print(text.find("python")) # 9 -- index where "python" starts
print(text.find("java")) # -1 -- not found, returns -1 (no exception)
print(text.index("python")) # 9 -- same as find() when the substring exists
# text.index("java") # ValueError: substring not found -- raises instead!Checking Prefixes, Suffixes, and Counting
filename = "report_final.pdf"
print(filename.startswith("report")) # True
print(filename.endswith(".pdf")) # True
print(filename.endswith((".pdf", ".docx"))) # True -- can pass a tuple of options
text = "mississippi"
print(text.count("s")) # 4
print(text.count("ss")) # 2 (non-overlapping matches)Checking Character Composition
A family of .is...() methods let you check what kind of characters a string contains — handy for validating input.
print("12345".isdigit()) # True
print("abc123".isdigit()) # False
print("abc".isalpha()) # True
print("abc123".isalnum()) # True -- letters AND digits, no symbols
print(" ".isspace()) # True
print("HELLO".isupper()) # True
print("hello".islower()) # TrueQuick Reference: Most-Used String Methods
Method | Description |
|---|---|
.upper() / .lower() | Convert to all uppercase / all lowercase. |
.title() / .capitalize() | Capitalize each word / capitalize just the first letter. |
.strip() / .lstrip() / .rstrip() | Remove leading/trailing whitespace (or given characters). |
.split(sep) | Break a string into a list using a separator. |
.join(iterable) | Combine an iterable of strings using this string as the separator. |
.replace(old, new) | Return a copy with all (or limited) occurrences replaced. |
.find(sub) / .index(sub) | Locate a substring; find() returns -1, index() raises if missing. |
.startswith(x) / .endswith(x) | Check if the string starts or ends with a given value. |
.count(sub) | Count non-overlapping occurrences of a substring. |
.isdigit() / .isalpha() / .isalnum() | Check whether the string is all digits / letters / letters+digits. |
Method Chaining
Because every string method returns a new string, calls can be chained one after another for a compact pipeline of transformations.
messy = " Hello, WORLD! "
clean = messy.strip().lower().replace("!", ".")
print(clean) # hello, world.