Python Cheatsheet

This site is a reference for Python

Last updated on 14 June, 2021 at 09:50:16 Optimized for

Python started as a hobby project by Guido Van Rossum and was first released in 1991, as a successor to the ABC programming language. Python's design philosophy emphasizes code readability with its notable use of significant whitespace. It aims to help programmers write clear, logical code for small and large-scale projects. Popular frameworks include Django, Flask, Numpy, Scipy

Website logo
For the full experience we recommend viewing this website on a desktop or tablet.

String Methods

Used to manipulate or retrieve information on strings

Example Description
capitalize()

Return a copy of the string with its first character capitalized and the rest lowercased

center(width[, fillchar])

Return centered in a string of length width. Padding is done using the specified fillchar (default is a space)

count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]

decode

Decodes the string using the codec registered for encoding

encode([encoding[, errors]])

Return an encoded version of the string. Default encoding is the current default string encoding

endswith(suffix[, start[, end]])

Return True if the string ends with the specified suffix, otherwise return False

expandtabs([tabsize])

Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size

find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]

format(*args, **kwargs)

Perform a string formatting operation

index(sub[, start[, end]])

Like find(), but raise ValueError when the substring is not found

isalnum()

Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise

isalpha()

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise

isdigit()

Return true if all characters in the string are digits and there is at least one character, false otherwise

islower()

Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise

isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise

istitle()

Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones

isupper()

Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise

join(iterable)

Return a string which is the concatenation of the strings in the iterable iterable

ljust(width[, fillchar])

Return the string left justified in a string of length width

lower()

Return a copy of the string converted to lowercase

lstrip([chars])

Return a copy of the string with leading characters removed

partition(sep)

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator

replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new

rfind(sub[, start[, end]])

Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]

rindex(sub[, start[, end]])

Like rfind() but raises ValueError when the substring sub is not found

rjust(width[, fillchar])

Return the string right justified in a string of length width

rpartition(sep)

Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator

rsplit([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string

rstrip([chars])

Return a copy of the string with trailing characters removed

split([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string

splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries

startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False

strip([chars])

Return a copy of the string with the leading and trailing characters removed

swapcase

Return a copy of the string with uppercase characters converted to lowercase and vice versa

title()

Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase

translate(table[, deletechars])

Return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256

upper()

Return a copy of the string converted to uppercase

zfill(width)

Return the numeric string left filled with zeros in a string of length width

isnumeric()

Return True if there are only numeric characters in S, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH

isdecimal()

Return True if there are only decimal characters in S, False otherwise

Random

Use randomly generated numbers

Command Description
seed([x])

Initialize the basic random number generator

getstate()

Return an object capturing the current internal state of the generator

setstate(state)

State should have been obtained from a previous call to getstate(), and setstate() restores the internal state of the generator to what it was at the time setstate() was called

jumpahead(n)

Change the internal state to one different from and likely far away from the current state

getrandbits(k)

Returns a python long int with k random bits

randrange([start], stop[, step])

Return a randomly selected element from range(start, stop, step)

randint(a,b)

Return a random integer N such that a <= N <= b

choice(seq)

Return a random element from the non-empty sequence seq

shuffle(x[,random])

Shuffle the sequence x in place

sample(population,k)

Return a k length list of unique elements chosen from the population sequence

random()

Return the next random floating point number in the range [0.0, 1.0)

uniform(a,b)

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a

triangular(low,high,mode)

Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds

betavariate(alpha,beta)

Beta distribution

expovariate(lambd)

Exponential distribution

gammavariate(alpha,beta)

Gamma distribution

gauss(mu,sigma)

Gaussian distribution

lognormvariate(mu,sigma)

Log normal distribution

normalvariate(mu,sigma)

Normal distribution

vonmisesvariate(mu,kappa)

Mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero

paretovariate(alpha)

Pareto distribution

weibullvariate(alpha,beta)

Weibull distribution

Numbers

Command Description
ceil(x)

Return the ceiling of x as a float, the smallest integer value greater than or equal to x

copysign(x,y)

Return x with the sign of y

fabs(x)

Return the absolute value of x

factorial(x)

Return x factorial

floor(x)

Return the floor of x as a float, the largest integer value less than or equal to x

fmod(x,y)

Return fmod(x, y), as defined by the platform C library

frexp(x)

Return the mantissa and exponent of x as the pair (m, e)

fsum(iterable)

Return an accurate floating point sum of values in the iterable

isinf(x)

Check if the float x is positive or negative infinity

isnan(x)

Check if the float x is a NaN (not a number)

ldexp(x,i)

Return x * (2**i)

modf()

Return the fractional and integer parts of x

trunc()

Return the Real value x truncated to an Integral (usually a long integer)

Powers and Logarithms

Command Description
exp(x)

Return e**x

log(x[,base])

With one argument, return the natural logarithm of x (to base e)

log1p(x)

Return the natural logarithm of 1+x (base e)

log10(x)

Return the base-10 logarithm of x

pow(x,y)

Return x raised to the power y

sqrt(x)

Return the square root of x

Trigonometry

Command Description
acos(x)

Return the arc cosine of x, in radians

asin(x)

Return the arc sine of x, in radians

atan(x)

Return the arc tangent of x, in radians

atan2(y,x)

Return atan(y / x), in radians

cos(x)

Return the cosine of x radians

hypot(x,y)

Return the Euclidean norm, sqrt(x*x + y*y)

sin(x)

Return the sine of x radians

tan(x)

Return the tangent of x radians

degrees(x)

Converts angle x from radians to degrees

radians(x)

Converts angle x from degrees to radians

acosh(x)

Return the inverse hyperbolic cosine of x

asinh(x)

Return the inverse hyperbolic sine of x

atanh(x)

Return the inverse hyperbolic tangent of x

cosh(x)

Return the hyperbolic cosine of x

sinh(x)

Return the hyperbolic sine of x

tanh(x)

Return the hyperbolic tangent of x

File Methods

Command Description
close()

Close the file

flush()

Flush the internal buffer, like stdio‘s fflush()

fileno()

Return the integer “file descriptor” that is used by the underlying implementation to request I/O operations from the operating system

isatty()

Return True if the file is connected to a tty(-like) device, else False

next()

A file object is its own iterator, for example iter(f) returns f (unless f is closed)

read([size])

Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes)

readline([size])

Read one entire line from the file

readlines([sizehint])

Read until EOF using readline() and return a list containing the lines thus read

xreadlines()

This method returns the same thing as iter(f)

seek(offset[, whence])

Set the file’s current position, like stdio‘s fseek()

tell()

Return the file’s current position, like stdio‘s ftell()

truncate([size])

Truncate the file’s size

write(str)

Write a string to the file

writelines(sequence)

Write a sequence of strings to the file

File Attributes

Command Description
closed

Bool indicating the current state of the file object

encoding

The encoding that this file uses

errors

The Unicode error handler used along with the encoding

mode

The I/O mode for the file

name

If the file object was created using open(), the name of the file

newlines

If Python was built with the --with-universal-newlines option to configure (the default) this read-only attribute exists, and for files opened in universal newline read mode it keeps track of the types of newlines encountered while reading the file

softspace

Boolean that indicates whether a space character needs to be printed before another value when using the print statement

List Methods

Command Description
append(x)

Append a new item with value x to the end of the array

buffer_info()

Return a tuple (address, length) giving the current memory address and the length in elements of the buffer used to hold array’s contents

byteswap()

“Byteswap” all items of the array

count(x)

Return the number of occurrences of x in the array

extend(iterable)

Append items from iterable to the end of the array

fromfile(f,n)

Read n items (as machine values) from the file object f and append them to the end of the array

fromlist(list)

Append items from the list

fromstring(s)

Appends items from the string, interpreting the string as an array of machine values (as if it had been read from a file using the fromfile() method)

fromunicode(s)

Extends this array with data from the given unicode string

index(x)

Return the smallest i such that i is the index of the first occurrence of x in the array

insert(i,x)

Insert a new item with value x in the array before position i

pop([i])

Removes the item with the index i from the array and returns it

remove(x)

Remove the first occurrence of x from the array

reverse()

Reverse the order of the items in the array

tofile(f)

Write all items (as machine values) to the file object f

tolist()

Convert the array to an ordinary list with the same items

tostring()

Convert the array to an array of machine values and return the string representation (the same sequence of bytes that would be written to a file by the tofile() method.)

tounicode()

Convert the array to a unicode string

Sets

Command Description
isdisjoint(other)

Return True if the set has no elements in common with other

issubset(others)

Test whether every element in the set is in others

issuperset

Test whether every element in other is in the set

union(other...)

Return a new set with elements from the set and all others

intersection(other, ...)

Return a new set with elements common to the set and all others

difference(other...)

Return a new set with elements in the set that are not in the others

symmetric_difference(other)

Return a new set with elements in either the set or other but not both

copy()

Return a new set with a shallow copy of s

update()

Update the set, adding elements from all others

intersection_update()

Update the set, adding elements from all others

difference_update()

Update the set, removing elements found in others

symmetric_difference_update()

Update the set, keeping only elements found in either set, but not in both

add(elem)

Add element elem to the set

remove()

Remove element elem from the set. Raises KeyError if elem is not contained in the set

discard(elem)

Remove element elem from the set if it is present

pop()

Remove element elem from the set if it is present

clear()

Remove all elements from the set

Dictionary Methods

Command Description
clear()

Remove all items from the dictionary

copy()

Return a shallow copy of the dictionary

fromkeys(seq[, value])

Create a new dictionary with keys from seq and values set to value

get(key[, default])

Return the value for key if key is in the dictionary, else default

has_key(key)

Test for the presence of key in the dictionary. has_key() is deprecated in favor of key in d

items()

Return a copy of the dictionary’s list of (key, value) pairs

iteritems()

Return an iterator over the dictionary’s (key, value) pairs. See the note for dict.items()

iterkeys()

Return an iterator over the dictionary’s keys. See the note for dict.items()

itervalues()

Return an iterator over the dictionary’s values. See the note for dict.items()

keys()

Return a copy of the dictionary’s list of keys. See the note for dict.items()

pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default

popitem()

Remove and return an arbitrary (key, value) pair from the dictionary

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default

update([other])

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None

values

Return a copy of the dictionary’s list of values. See the note for dict.items()

Online Resources & Books