iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

String Methods

Quick reference to Python's string methods. Strings are immutable — every method returns a new string.

Case

MethodReturns
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

MethodReturns
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)

MethodReturns
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

MethodReturns
'{} {}'.format(a, b)Positional formatting.
'%s' % aprintf-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. ()

Test yourself

Q1. Trim whitespace with…
Q2. Split with default separator splits on…
Q3. "abc".replace returns…

Discussion

Loading…