Python Standard Methods Reference

String Methods

Method Description
capitalize() Returns a string with the first character capitalized and the rest lowercased
casefold() Returns a lowercase string, more aggressive than lower() for caseless matching
center(width, fillchar) Returns a centered string padded with fillchar
count(sub, start, end) Returns the number of occurrences of substring
encode(encoding, errors) Returns an encoded version of the string
endswith(suffix, start, end) Returns True if string ends with the specified suffix
expandtabs(tabsize) Sets the tab size to the specified number of whitespaces
find(sub, start, end) Returns the lowest index of substring or -1 if not found
format(*args, **kwargs) Formats the string using placeholders
format_map(mapping) Formats the string using a dictionary
index(sub, start, end) Like find() but raises ValueError if not found
isalnum() Returns True if all characters are alphanumeric
isalpha() Returns True if all characters are alphabetic
isascii() Returns True if all characters are ASCII
isdecimal() Returns True if all characters are decimal characters
isdigit() Returns True if all characters are digits
isidentifier() Returns True if string is a valid identifier
islower() Returns True if all cased characters are lowercase
isnumeric() Returns True if all characters are numeric
isprintable() Returns True if all characters are printable
isspace() Returns True if all characters are whitespace
istitle() Returns True if string is titlecased
isupper() Returns True if all cased characters are uppercase
join(iterable) Joins elements of an iterable with string as separator
ljust(width, fillchar) Returns a left-justified string padded to width
lower() Returns a lowercase version of the string
lstrip(chars) Returns a string with leading characters removed
maketrans(x, y, z) Returns a translation table for translate()
partition(sep) Splits string at first occurrence of separator
replace(old, new, count) Returns string with occurrences of old replaced with new
rfind(sub, start, end) Returns highest index of substring or -1 if not found
rindex(sub, start, end) Like rfind() but raises ValueError if not found
rjust(width, fillchar) Returns a right-justified string padded to width
rpartition(sep) Splits string at last occurrence of separator
rsplit(sep, maxsplit) Splits string from the right
rstrip(chars) Returns a string with trailing characters removed
split(sep, maxsplit) Splits string into a list using separator
splitlines(keepends) Splits string at line breaks
startswith(prefix, start, end) Returns True if string starts with the specified prefix
strip(chars) Returns a string with leading and trailing characters removed
swapcase() Returns a string with uppercase/lowercase swapped
title() Returns a titlecased string
translate(table) Returns a string translated using a translation table
upper() Returns an uppercase version of the string
zfill(width) Pads string with zeros on the left

List Methods

Method Description
append(element) Adds an element to the end of the list
clear() Removes all elements from the list
copy() Returns a shallow copy of the list
count(value) Returns the number of times value appears in the list
extend(iterable) Adds all elements from an iterable to the end of the list
index(value, start, stop) Returns the index of the first occurrence of value
insert(index, element) Inserts an element at the specified index
pop(index) Removes and returns the element at index (default: -1)
remove(value) Removes the first occurrence of value
reverse() Reverses the list in place
sort(key, reverse) Sorts the list in place

Dictionary Methods

Method Description
clear() Removes all items from the dictionary
copy() Returns a shallow copy of the dictionary
fromkeys(keys, value) Creates a new dictionary with keys and optional value
get(key, default) Returns the value for key or default if not found
items() Returns a view of dictionary's key-value pairs
keys() Returns a view of dictionary's keys
pop(key, default) Removes and returns value for key or default if not found
popitem() Removes and returns an arbitrary key-value pair
setdefault(key, default) Returns value for key, inserting default if not found
update(other) Updates dictionary with key-value pairs from other
values() Returns a view of dictionary's values

Set Methods

Method Description
add(element) Adds an element to the set
clear() Removes all elements from the set
copy() Returns a shallow copy of the set
difference(*others) Returns elements in set but not in others
difference_update(*others) Removes elements found in others from the set
discard(element) Removes element from set if present
intersection(*others) Returns elements common to set and others
intersection_update(*others) Updates set with elements common to all
isdisjoint(other) Returns True if sets have no common elements
issubset(other) Returns True if set is a subset of other
issuperset(other) Returns True if set is a superset of other
pop() Removes and returns an arbitrary element
remove(element) Removes element from set, raises KeyError if not found
symmetric_difference(other) Returns elements in either set but not both
symmetric_difference_update(other) Updates set with symmetric difference
union(*others) Returns a new set with elements from all sets
update(*others) Updates set with elements from others

Tuple Methods

Method Description
count(value) Returns the number of times value appears in the tuple
index(value, start, stop) Returns the index of the first occurrence of value

File Methods

Method Description
close() Closes the file
fileno() Returns the file descriptor as an integer
flush() Flushes the internal buffer
isatty() Returns True if file is connected to a terminal
read(size) Reads and returns size bytes or entire file
readable() Returns True if file can be read
readline(size) Reads and returns one line from the file
readlines(hint) Reads and returns a list of lines
seek(offset, whence) Moves file position to offset
seekable() Returns True if file supports random access
tell() Returns the current file position
truncate(size) Resizes the file to size bytes
writable() Returns True if file can be written to
write(string) Writes string to file and returns number of characters written
writelines(lines) Writes a list of lines to the file

Built-in Functions

Function Description
abs(x) Returns the absolute value of a number
all(iterable) Returns True if all elements in iterable are true
any(iterable) Returns True if any element in iterable is true
ascii(object) Returns a string with printable representation using escape sequences
bin(x) Converts an integer to a binary string prefixed with "0b"
bool(x) Converts a value to a Boolean
bytearray(source, encoding) Returns a new array of bytes
bytes(source, encoding) Returns a new bytes object
callable(object) Returns True if object appears callable
chr(i) Returns a string representing a character whose Unicode code point is the integer i
classmethod(function) Returns a class method for function
compile(source, filename, mode) Compiles source into a code object
complex(real, imag) Returns a complex number
delattr(object, name) Deletes an attribute from an object
dict(**kwargs) Creates a new dictionary
dir(object) Returns list of attributes and methods of an object
divmod(a, b) Returns a tuple of quotient and remainder
enumerate(iterable, start) Returns an enumerate object with index and value pairs
eval(expression, globals, locals) Evaluates a Python expression
exec(object, globals, locals) Executes Python code dynamically
filter(function, iterable) Constructs an iterator from elements of iterable for which function returns true
float(x) Converts a value to a floating point number
format(value, format_spec) Formats a value according to format_spec
frozenset(iterable) Returns an immutable frozenset object
getattr(object, name, default) Returns the value of a named attribute of an object
globals() Returns a dictionary of the current global symbol table
hasattr(object, name) Returns True if object has the named attribute
hash(object) Returns the hash value of an object
help(object) Invokes the built-in help system
hex(x) Converts an integer to a hexadecimal string prefixed with "0x"
id(object) Returns the identity (memory address) of an object
input(prompt) Reads a line from input
int(x, base) Converts a value to an integer
isinstance(object, classinfo) Returns True if object is an instance of classinfo or its subclass
issubclass(class, classinfo) Returns True if class is a subclass of classinfo
iter(object, sentinel) Returns an iterator object
len(s) Returns the length (number of items) of an object
list(iterable) Creates a new list
locals() Returns a dictionary of the current local symbol table
map(function, iterable) Applies function to every item of iterable
max(iterable, key, default) Returns the largest item in an iterable
memoryview(object) Returns a memory view object
min(iterable, key, default) Returns the smallest item in an iterable
next(iterator, default) Retrieves the next item from an iterator
object() Returns a new featureless object
oct(x) Converts an integer to an octal string prefixed with "0o"
open(file, mode, encoding) Opens a file and returns a file object
ord(c) Returns an integer representing the Unicode code point of a character
pow(base, exp, mod) Returns base to the power exp
print(*objects, sep, end, file) Prints objects to the text stream file
property(fget, fset, fdel, doc) Returns a property attribute
range(start, stop, step) Returns an immutable sequence of numbers
repr(object) Returns a string containing a printable representation of an object
reversed(seq) Returns a reverse iterator
round(number, ndigits) Rounds a number to a given precision
set(iterable) Creates a new set object
setattr(object, name, value) Sets the value of a named attribute of an object
slice(start, stop, step) Returns a slice object
sorted(iterable, key, reverse) Returns a new sorted list from the items in iterable
staticmethod(function) Returns a static method for function
str(object, encoding, errors) Returns a string version of an object
sum(iterable, start) Sums start and the items of an iterable
super(type, object) Returns a proxy object that delegates method calls to a parent or sibling class
tuple(iterable) Creates a new tuple
type(object) Returns the type of an object
vars(object) Returns the __dict__ attribute of an object
zip(*iterables) Returns an iterator of tuples

Built-in Functions (Common Object Methods)

Method Description
__init__(self, ...) Constructor method, called when object is created
__str__(self) Returns a string representation for print()
__repr__(self) Returns an official string representation
__len__(self) Returns the length of the object
__getitem__(self, key) Implements indexing/key access
__setitem__(self, key, value) Implements assignment to indexed position
__delitem__(self, key) Implements deletion of indexed item
__iter__(self) Returns an iterator object
__next__(self) Returns the next item from iterator
__contains__(self, item) Implements membership test with 'in'
__call__(self, ...) Makes object callable like a function
__enter__(self) Enters context manager (with statement)
__exit__(self, ...) Exits context manager
__eq__(self, other) Implements equality comparison ==
__ne__(self, other) Implements inequality comparison !=
__lt__(self, other) Implements less than comparison <
__le__(self, other) Implements less than or equal <=
__gt__(self, other) Implements greater than comparison >
__ge__(self, other) Implements greater than or equal >=
__add__(self, other) Implements addition operator +
__sub__(self, other) Implements subtraction operator -
__mul__(self, other) Implements multiplication operator *
__truediv__(self, other) Implements division operator /
__floordiv__(self, other) Implements floor division operator //
__mod__(self, other) Implements modulo operator %
__pow__(self, other) Implements power operator **

Number Methods (int, float)

Method Description
bit_length() Returns number of bits needed to represent integer
conjugate() Returns the complex conjugate
from_bytes(bytes, byteorder) Returns integer from byte representation
to_bytes(length, byteorder) Returns byte representation of integer
as_integer_ratio() Returns a pair of integers whose ratio equals the number
hex() Returns hexadecimal string representation
is_integer() Returns True if float is an integer value

Bytes and Bytearray Methods

Method Description
capitalize() Returns a copy with first byte capitalized
center(width, fillbyte) Returns centered bytes padded with fillbyte
count(sub, start, end) Returns number of occurrences of subsequence
decode(encoding, errors) Decodes bytes to a string
endswith(suffix, start, end) Returns True if bytes end with suffix
find(sub, start, end) Returns lowest index of subsequence
hex(sep, bytes_per_sep) Returns hexadecimal representation
index(sub, start, end) Like find() but raises ValueError if not found
isalnum() Returns True if all bytes are alphanumeric
isalpha() Returns True if all bytes are alphabetic
isdigit() Returns True if all bytes are digits
islower() Returns True if all cased bytes are lowercase
isspace() Returns True if all bytes are whitespace
isupper() Returns True if all cased bytes are uppercase
join(iterable) Joins elements with bytes as separator
lower() Returns lowercase version of bytes
lstrip(bytes) Returns bytes with leading bytes removed
replace(old, new, count) Returns bytes with old replaced by new
split(sep, maxsplit) Splits bytes into list using separator
startswith(prefix, start, end) Returns True if bytes start with prefix
strip(bytes) Returns bytes with leading/trailing bytes removed
upper() Returns uppercase version of bytes

Iterator and Generator Methods

Method Description
__iter__() Returns the iterator object itself
__next__() Returns the next item from the iterator
send(value) Sends a value to the generator
throw(type, value, traceback) Raises an exception in the generator
close() Closes the generator