Python · Chapter 9 of 45
Python String Methods
Strings come with dozens of useful methods. Because strings are immutable, every method returns a NEW string — the original is unchanged.
Common methods: `upper()`, `lower()`, `strip()`, `replace()`, `split()`, `join()`, `startswith()`, `find()`.
Case and whitespace
`upper()` and `lower()` change case. `strip()` removes surrounding whitespace.
Splitting and joining
`split(sep)` breaks a string into a list. `sep.join(list)` glues them back together.
Example 1 (python)
s = " Hello World "
print(s.strip())
print(s.strip().lower())Output
Hello World
hello worldChain methods left-to-right.
Example 2 (python)
csv = "apple,banana,cherry"
fruits = csv.split(",")
print(fruits)
print(" | ".join(fruits))Output
['apple', 'banana', 'cherry']
apple | banana | cherrysplit() and join() are inverses.
Key points
- String methods return NEW strings; originals stay unchanged.
- `strip()` trims whitespace on both sides.
- `replace(old, new)` swaps every occurrence.
- `split()` and `join()` convert between strings and lists.
💡 Note: `find()` returns -1 when not found; `index()` raises an error. Choose based on how you want to handle a miss.
