Reference
Methods
str, bytes, list, dict, and set carry built-in methods, plus a small set on int and float. The set is curated for common operations. Missing variants are noted per section.
tuple and frozenset have no methods. (1, 2).count(1) raises AttributeError. Frozensets use the operators from Set instead.
HELLO 1 1
String methods
Case transforms
upper, lower, capitalize, title, casefold, swapcase.
titletitlecases each maximal run of letters.casefoldis the same simple lowercasing aslower. It does not expand characters.'ß'.casefold()stays'ß'instead of becoming'ss'.
HELLO hello Hello world Hello World hello straße hELLO wORLD
Whitespace
strip, lstrip, rstrip remove whitespace, or any character in the optional string argument.
hi hi hi hello
Predicates
isdigit, isalpha, isalnum, isspace, isupper, islower, istitle.
- All return
Falseon an empty string. - The cased predicates also require at least one cased character.
- Every predicate follows the Unicode 15 character tables.
"٣".isdigit()isTrueand"½".isdigit()isFalse.
True True True True True True True
Not provided are isascii, isidentifier, isnumeric, isdecimal, and isprintable.
Search and count
findandrfindreturn a code-point index, or-1on a miss.indexandrindexraiseValueErroron a miss.countcounts non-overlapping occurrences.startswithandendswithaccept a single string or a tuple of strings.- All of these take optional
startandendcode-point bounds.
True True 2 5 3 -1 2
Split, join, replace
split()with no argument orNonesplits on whitespace runs.- An explicit separator splits on every occurrence. An empty separator raises
ValueError. splitandrsplittake an optionalmaxsplit.replace(old, new)takes an optionalcountcap.splitlines()drops the line separators and has nokeependsmode.partitionandrpartitionsplit once into a(head, sep, tail)tuple.removeprefixandremovesuffixstrip an affix when present.
['a', 'b', 'c']
['a', 'b,c']
['a b', 'c']
['hello', 'world']
a,b,c
bbaa
bar
['a', 'b', 'c']
('foo', ':', 'bar:baz')
('foo:bar', ':', 'baz')Padding
center,ljust,rjusttake(width[, fill]).zfill(width)pads with leading zeros after any sign.- Widths are measured in code points, not bytes.
- A multi-character
fillraisesTypeError. expandtabs([tabsize])replaces tabs with spaces up to the next tab stop, default 8.
--abc-- hi... ...hi 00042 -0042 a bc **ñ**
Not provided are translate, maketrans, and format_map.
Formatting
str.format(*args) fills positional fields.
{}auto-numbers and{0}picks an index.- A spec after
:uses the format mini-language. - Keyword fields like
{name}are not supported.
The % operator does printf-style formatting.
- The verbs are
%s %r %d %i %u %x %X %o %f %F %e %E %g %G %c %%. - Flags, width, and
.precisionapply. *reads the width or precision from the next argument.- A tuple on the right spreads into the fields. Any other value is a single argument.
a and b
x-y-x
hi
3 apples, 1.5 kg
03.10|hi |Encoding
s.encode([encoding]) returns bytes. The encodings are "utf-8" (the default), "utf8", and "ascii".
- ASCII raises
UnicodeEncodeErroron non-ASCII input. It is a subclass ofValueError. - Any other encoding name raises
ValueError.
b'caf\xc3\xa9' b'hi'
Bytes methods
bytes carries the methods below. bytearray and memoryview do not exist.
| Method | Behavior |
|---|---|
decode([encoding[, errors]]) | Returns a string. The encodings match str.encode |
hex() | Lowercase hex with no separator option |
startswith, endswith | Take a single bytes value, no tuple form |
find, index | A byte offset. find gives -1 on a miss and index raises ValueError |
count | Non-overlapping occurrences |
replace(old, new[, count]) | Replaces every occurrence, or the first count |
split([sep[, maxsplit]]) | Splits on whitespace runs, or on every sep |
lower, upper | Change the case of ASCII bytes only |
strip, lstrip, rstrip | Trim ASCII whitespace, or any byte in the optional argument |
join(iterable) | Concatenates an iterable of bytes |
bytes.fromhex(s) | Parses a hex string, see fromhex |
find, index and count take optional start and end byte bounds.
The errors handler of decode takes three values.
"strict"is the default. It raisesUnicodeDecodeError, aValueError, on invalid UTF-8."ignore"drops the bad bytes."replace"substitutes U+FFFD.
Hello 48656c6c6f True True 2 2 b'HeLLo' [b'a', b'b', b'c'] b'abc' b'hi' b'a-b-c' �
fromhex
bytes.fromhex(s) parses a hex string into bytes. It is called on the type, not on a value.
- Each pair of hex digits becomes one byte, in either case.
- ASCII whitespace anywhere in
sis ignored. - A character that is not a hex digit raises
ValueError. - An odd number of digits raises
ValueError.
The builtin bytes_fromhex(s) does the same.
b'Hello' b'\xff\x00'
List methods
Query
index(value[, start[, end]])returns the first match and raisesValueErroron a miss. Negative bounds count from the end.count(value)counts matches.copy()returns a shallow copy.
1 3 2 [1, 2, 3, 2] [1, 2, 3, 2, 99]
Mutating
These return None and mutate in place.
append(x)adds one item.extend(iter)adds every item of any iterable.insert(i, x)inserts at an index.remove(x)deletes the first match and raisesValueErroron a miss.pop()removes and returns the last item,pop(i)the item at an index. Both raiseIndexErrorwhen the index is invalid.sort()acceptskey=fnandreverse=True. It follows the ordering rules of sorted.reverse()flips in place.clear()empties the list.
[99, 1, 2, 3, 4, 5, 6] 6 [1, 2, 3, 4, 5] 1 [2, 3, 4, 5]
Dict methods
Views
keys, values, items return views that read the dict live. A view taken earlier shows later changes. The keys and items views take the set operators and isdisjoint.
dict_keys(['a', 'b', 'c'])
dict_values([1, 2, 3])
dict_items([('a', 1), ('b', 2), ('c', 3)])
dict_keys(['a', 'b', 'c', 'd'])
{'a'}Lookup
get(key) returns the value or None. get(key, default) returns default on a miss.
1 None 0
Mutation
update(src)merges a dict, an iterable of length-2 pairs, or keyword arguments.pop(key)removes and returns the value. It raisesKeyErroron a miss unless a default is given.popitem()removes and returns the last inserted(key, value)pair. It raisesKeyErroron an empty dict.setdefault(key, default)inserts only when the key is missing and returns the stored value.clear()empties the dict in place. Aliases see the change.copy()returns a shallow copy.dict.fromkeys(iterable[, value])builds a new dict that maps each key tovalue, defaultNone.
{'a': 99, 'b': 2, 'c': 3, 'e': 5}
99 {'b': 2, 'c': 3, 'e': 5}
fallback
2
{'x': 0, 'y': 0}
('e', 5)Set methods
Mutation
add(x)inserts.remove(x)deletes and raisesKeyErroron a miss.discard(x)deletes silently.pop()removes and returns an arbitrary element. It raisesKeyErroron an empty set.update(*iterables)inserts from any number of iterables.clear()empties the set.copy()returns a shallow copy.
{4, 3, 2, 1}
{4, 3, 1}
True
set()Algebra
union,intersection,differencereturn fresh sets and accept any number of iterable arguments.symmetric_differencetakes exactly one.intersection_update,difference_update,symmetric_difference_updatemutate the receiver.issubset,issuperset,isdisjointtest relations.
The named methods accept any iterable. The operator forms are in Set.
[1, 2, 3, 4, 5] [2, 4] True True True
int and float methods
int carries these methods. Arguments pass by position only.
bit_length()gives the bits needed for the absolute value,0for zero.bit_count()gives the number of set bits.to_bytes([length[, byteorder]])writes the value unsigned, withlength1 andbyteorder"big"by default. A negative value or one that does not fit raisesOverflowError.int.from_bytes(bytes[, byteorder])is called on the type. It reads the bytes unsigned,"big"by default. A value past the signed 128-bit range raisesOverflowError.
float carries is_integer().
8 8 b'\x03\xe8' b'\xe8\x03' 1000 True False
The builtins int_to_bytes and int_from_bytes are the same methods as functions, with every argument required.