reference
5 min read
·
lesson 2 of 16 in Reference
Python String Methods Cheat Sheet
1 · The lesson
readQuick reference for Python's str type — creating, slicing, searching, transforming, formatting. Strings are immutable: every method returns a new string. For the full tutorial, see Strings.
Creating
python
a = 'single' b = "double" c = """triple spans lines""" d = r"C:\Users\raw\no\escapes" # raw — backslashes literal e = b"bytes" # bytes, not str f = "concat" + "enation" g = "repeat" * 3 # 'repeatrepeatrepeat' h = str(42) # from anything: '42'
Indexing & Slicing
python
s = "python" s[0] # 'p' first s[-1] # 'n' last s[1:4] # 'yth' [start:stop) s[:3] # 'pyt' s[3:] # 'hon' s[::2] # 'pto' every 2nd s[::-1] # 'nohtyp' reverse len(s) # 6
Inspecting
| Method | What it does | Example | Returns |
|---|---|---|---|
len(s) | Length | len("abc") | 3 |
sub in s | Membership | "th" in "python" | True |
s.count(sub) | Occurrences | "banana".count("a") | 3 |
s.find(sub) | First index or -1 | "hello".find("l") | 2 |
s.rfind(sub) | Last index or -1 | "hello".rfind("l") | 3 |
s.index(sub) | First index, raises ValueError | "hello".index("z") | ValueError |
s.startswith(p) | Prefix check | "file.py".startswith("file") | True |
s.endswith(p) | Suffix check | "file.py".endswith(".py") | True |
s.isdigit() | All digits 0-9 | "123".isdigit() | True |
s.isalpha() | All letters | "abc".isalpha() | True |
s.isalnum() | Letters or digits | "abc123".isalnum() | True |
s.isspace() | All whitespace | " \n".isspace() | True |
s.islower() / isupper() | Case check | "abc".islower() | True |
Case
| Method | Example | Returns |
|---|---|---|
s.upper() | "hi".upper() | 'HI' |
s.lower() | "HI".lower() | 'hi' |
s.title() | "hi there".title() | 'Hi There' |
s.capitalize() | "hello world".capitalize() | 'Hello world' |
s.swapcase() | "Hi There".swapcase() | 'hI tHERE' |
s.casefold() | "Straße".casefold() | 'strasse' (aggressive lower, use for compare) |
Trimming
python
" hi ".strip() # 'hi' " hi ".lstrip() # 'hi ' " hi ".rstrip() # ' hi' "xxhixx".strip("x") # 'hi' any char in set "www.site.com".strip("wcom.") # 'site' — chars, not substring!
Splitting & Joining
| Method | Example | Returns |
|---|---|---|
s.split(sep) | "a,b,c".split(",") | ['a','b','c'] |
s.split() | " a b\tc ".split() | ['a','b','c'] (any whitespace) |
s.split(sep, n) | "a,b,c".split(",", 1) | ['a','b,c'] |
s.rsplit(sep, n) | "a,b,c".rsplit(",", 1) | ['a,b','c'] |
s.splitlines() | "a\nb\n".splitlines() | ['a','b'] |
s.partition(sep) | "key=val".partition("=") | ('key','=','val') |
sep.join(iter) | ",".join(['a','b']) | 'a,b' |
Replacing
python
"hello".replace("l", "L") # 'heLLo' "hello".replace("l", "L", 1) # 'heLlo' max 1 tbl = str.maketrans("aeiou", "AEIOU") "hello".translate(tbl) # 'hEllO' "hello".translate(str.maketrans("", "", "aeiou")) # 'hll' — delete
Formatting
python
name, n = "Ada", 42 f"{name} is {n}" # f-string (preferred, 3.6+) "{} is {}".format(name, n) # .format() "%s is %d" % (name, n) # legacy % — avoid in new code
Format spec mini-reference (f"{value:spec}")
| Spec | Meaning | Example | Output |
|---|---|---|---|
.2f | 2 decimal places | f"{3.14159:.2f}" | '3.14' |
, | Thousands separator | f"{1000000:,}" | '1,000,000' |
>10 | Right-align width 10 | f"{'hi':>10}" | ' hi' |
<10 | Left-align | f"{'hi':<10}" | 'hi ' |
^10 | Centre | f"{'hi':^10}" | ' hi ' |
0>3 | Pad with zeros | f"{7:0>3}" | '007' |
e | Scientific | f"{12345:.2e}" | '1.23e+04' |
% | Percent | f"{0.5:.0%}" | '50%' |
b/o/x | Binary/oct/hex | f"{255:x}" | 'ff' |
See F-Strings for the full guide.
Encoding
python
"café".encode() # b'caf\xc3\xa9' default utf-8 "café".encode("utf-16") b'caf\xc3\xa9'.decode() # 'café' # Escape sequences "\n" # newline "\t" # tab "\\" # literal backslash "\"" # literal quote "é" # é (unicode)
Common Patterns
python
# Slug text.strip().lower().replace(" ", "-") # Pad str(7).zfill(4) # '0007' f"{7:0>4}" # '0007' # Reverse s[::-1] # Join list of ints to CSV ",".join(str(x) for x in [1,2,3]) # '1,2,3' # Strip extension "report.pdf".removesuffix(".pdf") # 'report' (3.9+) "file_log".removeprefix("file_") # 'log' (3.9+) # Check multiple suffixes name.endswith((".jpg", ".png", ".gif"))
setup added so this can run · defines s, name, text
# Lightweight mock for objects whose attributes/methods aren't critical class _AutoMock: def __init__(self, name='mock'): self._name = name def __getattr__(self, k): return _AutoMock(self._name + '.' + k) def __call__(self, *a, **kw): print('-> ' + self._name + '() called') return _AutoMock(self._name + '()') def __repr__(self): return '<mock ' + self._name + '>' def __str__(self): return '<mock ' + self._name + '>' def __bool__(self): return True def __iter__(self): return iter([]) def __len__(self): return 0 def __getitem__(self, k): return _AutoMock(self._name + '[...]') def __setitem__(self, k, v): pass def __enter__(self): return self def __exit__(self, *a): return False async def __aenter__(self): return self async def __aexit__(self, *a): return False def __add__(self, o): return self def __radd__(self, o): return self def __sub__(self, o): return self def __mul__(self, o): return self def __rmul__(self, o): return self def __truediv__(self, o): return self def __eq__(self, o): return isinstance(o, _AutoMock) def __hash__(self): return hash(self._name) def __lt__(self, o): return True def __le__(self, o): return True def __gt__(self, o): return False def __ge__(self, o): return False def __mro_entries__(self, bases): return (object,) s = ["alpha", "beta", "gamma"] name = _AutoMock('name') text = _AutoMock('text')
Common Errors
| Error | Cause | Fix |
|---|---|---|
TypeError: 'str' object does not support item assignment | s[0] = "X" | Strings are immutable — build new: "X" + s[1:]. See full page |
AttributeError: 'str' object has no attribute 'append' | Treating string like list | Use +, +=, or "".join(parts) |
ValueError: substring not found | .index(x) when x absent | Use .find() (returns -1) or guard with in |
TypeError: can only concatenate str (not "int") to str | "x" + 5 | Convert: "x" + str(5) or use f-string |
UnicodeDecodeError | Wrong codec on .decode() | Specify correct encoding, e.g. .decode("latin-1") |
See Also
Practice this
on practicepython.inShort exercises that run in your browser and tell you what your code actually did, not just whether a test passed.