String Methods
Quick reference to Python's string methods. Strings are immutable — every method returns a new string.
Case
| Method | Returns |
|---|---|
s.upper() / s.lower() | Case-converted copy. |
s.title() / s.capitalize() | Title / sentence case. |
s.swapcase() | Flip cases. |
s.casefold() | Aggressive lower for caseless compare. |
Whitespace
strip / lstrip / rstrip — trim chars (default: whitespace).
Search & test
| Method | Returns |
|---|---|
s.startswith(prefix) / s.endswith(suffix) | True if matches. |
s.find(sub) / s.rfind(sub) | Index or -1. |
s.index(sub) | Like find but raises ValueError if absent. |
s.count(sub) | Number of non-overlapping occurrences. |
s.isdigit() / s.isalpha() / s.isalnum() | Character class tests. |
s.isspace() / s.isupper() / s.islower() | More tests. |
Modify (returning new)
| Method | Returns |
|---|---|
s.replace(a, b, n=) | Replace. |
s.removeprefix(p) / s.removesuffix(p) | Strip a known prefix/suffix (3.9+). |
s.split(sep, maxsplit=) | List of pieces. |
s.rsplit / s.splitlines() | Variants. |
s.partition(sep) | (before, sep, after) — useful for "split once". |
sep.join(iter) | Join an iterable of strings. |
s.zfill(n) | Zero-pad to length n. |
s.ljust(n) / s.rjust(n) / s.center(n) | Pad to width. |
Format
| Method | Returns |
|---|---|
'{} {}'.format(a, b) | Positional formatting. |
'%s' % a | printf-style (legacy). |
f'{a:.2f}' | f-strings (preferred). |
s.encode('utf-8') | str → bytes. |
Tip: For multi-line text manipulation,
textwrap in the standard library has dedent, fill, and shorten — saves rolling your own.Example
Example
s = ' Hello, Python '
print(s.strip())
print(s.lower())
print(s.replace('Python', 'world'))
print('-'.join(['a', 'b', 'c']))
print('abc'.startswith('a'))
Try it Yourself »
Exercise
Trim leading and trailing whitespace.
s.
()
Five letters.
Discussion
Loading…