Python Library functions

There are many libraries included with Python. The sections below presents the most usefull - builtin, string, math, random and datetime. See "Library Reference" for reference in Python 2.1 Documentation (available at http://python.org/doc/2.1/lib/lib.html).

Built-in functions

Table 14.7. List of built-in Python functions. See Built-in Functions for a complete reference.

Function nameSyntaxDescription
__import__
__import__(name[, globals[, locals[, fromlist]]])
This function can be used to import a Gython module whose name is known only at runtime.
abs
abs(x)
Returns the absolute value of an integer or floating point number or computes the modulus of a complex number.
apply
apply(function, args[, keywords])
Calls the function objects passing the list args as the list of arguments. The function argument must be a calllable objects (a user-defined or built-in function or method, or a class object). If the optional keywords argument is present, it must be a dictionary whose keys are strings. It specifies keyword arguments to be added to the end of the the argument list.
buffer
buffer(object[, offset[, size]])
Creates a reference (buffer object) pointing to object starting at offset (or the beginning of object, if offset is omitted) and with the length specified by size (or extending to the end of object, if size is omitted).
callable
callable(object)
Returns true if object is callable, false otherwise.
chr
chr(i)
Returns a string of one character with ASCII code i.
cmp
cmp(x, y)
Compares the objects x and y and returns a negative value if x < y, zero if x = y and a positive value if x > y.
coerce
coerce(x, y)
Returns a tuple consisting otf two numeric arguments x and y converted to a common type.
compile
compile(string, filename, kind)
Compiles the string into a code object. The filename argument should give the file from which the code was read; pass e.g. '<string>' if it wasn't read from a file. The kind argument specifies what kind of code must be compiled; it can be 'exec' if string consists of a sequence of statements, 'eval' if it consists of a single expression, or 'single' if it consists of a single interactive statement.
complex
complex(real[, imag])
Creates a complex number with the value real + imag*j.
delattr
delattr(object, name)
Deletes the attribute name (which should be a string) of object.
dir
dir([object])
Without arguments, return the list of names in the current local symbol table. With an argument, attempts to return a list of valid attributes for object.
divmod
divmod(a, b)
Returns the quotient and remainder of a and b using long division.
eval
eval(expression[, globals[, locals]])
The arguments are a string and two optional dictionaries. The expression argument is parsed and evaluated as a Python expression using globals and locals as the global and local name space.
execfile
execfile(file[, globals[, locals]])
The arguments are a file name and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements using globals and locals as the global and local namespace.
filter
filter(function, list)
Returns a list from those elements of list for which function returns true. If functionNone returns a list of non-zero and non-empty elements of list.
float
float(x)
Converts a string or number x to a floating point number.
getattr
getattr(object, name[, default])
Returns the value of the named attributed of object. (name must be a string). If the string is the name of one of the object's attributes, the result is the value of that attribute. If the named attribute does not exists default is returned.
globals
globals()
Returns a dictionary representing the current global symbol table.
hasattr
hasattr(object, name)
The arguments are an object and a string. The result is 1 if the string is the name of one of the object's attributes, 0 if not.
hash
hash(object)
Returns the hash value of object.
hex
hex(x)
Converts an integer number (of any size) to a hexadecimal string. The result is a valid Python expression.
id
id(object)
Returns the 'identity' of object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.
input
input([prompt])
Equivalent to eval(raw_input(prompt)).
int
int(x[, radix])
Converts the string or numerical variable x to an integer using radix as the base for the conversion. If radix is 0, the base is deduced from the content of x.
intern
intern(string)
Adds string to the list of interned strings and returns a copy of string. Interning strings is useful to gain a little performance on dictionary lookup - if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons can be performed faster.
isinstance
isinstance(object, class)
Returns true if object is an instance of class or its direct or indirect subclass. Also returns true if class is a type of object and object is of that type.
issubclass
issubclass(class1, class2)
Returns true if class1 is a direct or indirect subclass of class2.
len
len(s)
Returns the number of items in the object s. The argument may be a sequence (string, tuple or list), or a dictionary.
list
list(sequence)
Returns a list with the same items (nd order) as the ones in sequence.
locals
locals()
Returns a dictionary representing the current local symbol table.
long
long(x[, radix])
Converts the string or numerical variable x to a long integer using radix as the base for the conversion. If radix is 0, the base is deduced from the content of x.
map
map(function, list, ...)
Applies function to every item of list and returns a list of the results. If additional list arguments are passed, function must take that many arguments and is applied to the items of all lists in parallel; if one list is shorter than another it is assumed to be extended with None items.
max
max(s[, args...])
With a single sequence argument s returns the largest item of the sequence. With multiple arguments, returns the largest one.
min
min(s[, args...])
With a single sequence argument s returns the smallest item of the sequence. With multiple arguments, returns the smallest one.
oct
oct(x)
Converts the integer (or long integer) x to an octal string.
open
open(filename[, mode[, bufsize]])
Returns a new file object, enabling access to the file designated by filename; mode indicates how the file is to be opened: 'r' for reading, 'w' for writing (this truncates the existing file, 'a' for appending. Add + to the mode string to open the file for updating. Add b to open the file in binary mode (as opposed to text mode). By default the file is opend for reading. The optional bufsize argument specifies the file's desired buffer size: negative bufsize means use system default, 0 - unbuffered, 1 - line buffered, any other positive value means use the buffer of (approximately) that size.
ord
ord(c)
Returns the ASCII value of a one character string or Unicode character c.
pow
pow(x, y[, z])
Returns x to the power y (modulo z).
range
range([start,] stop[, step])
Returns a list containing an arithmetic progression. All arguments must be integers.
raw_input
raw_input([prompt])
If the prompt argument is present, it is written to standard output The function then reads a line from input, converts it to a string, and returns that.
reduce
reduce(function, sequence[, initializer])
Applies a two argument function cumulatively to the items of the sequence from left to right, so as to reduce it to a single value. If the optional initializer is present, it is added to the beginning of the list and serves as the result when sequence is empty.
reload
reload(module)
Re-parse and re-initializes a previously loaded module, for example after its source file has been edited.
repr
repr(object)
Returns a string containing a printable representation of object.
round
round(x[, n])
Returns a floating point value obtained by rounding x to n decimal points.
setattr
setattr(object, name, value)
Assigns value to the attribute denoted by the string name of object.
slice
slice([start,] stop[, step])
Returns a slice object representing the set of indices specified by range(start, stop, step).
str
str(object)
Returns a string containing a nicely printable representation of an object.
tuple
tuple(sequence)
Returns a tuple whose items are the same and in the same order as the items of sequence.
type
type(object)
Returns the type of object. The return value is a type object.
unichr
unichr(i)
Returns the Unicode string of one character whose Unicode code is the integer i.
unicode
unicode(string[, encoding[, errors]])
Decodes string using the codec specified by encoding. Error handling is done according to errors. The default behavior is to decode UTF-8 in strict mode.
vars
vars([object])
Without arguments, return a dictionary corresponding to the current local symbol table. With a module, class or class instance object as the argument (or anything else that has a __dict__ attribute), returns a dictionary corresponding to the object's symbol table.
xrange
xrange([start,] stop[, step])
Similar to range(), but returns an xrange object instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously.
zip
zip(seq1, ...)
Returns a list of tuples, where the n-th tuple contains the n-th elements from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.

String functions

Table 14.8. List of string functions. See String - common string operations for a complete reference.

Function nameSyntaxDescription
capitalize
capitalize(word)
Capitalizes the first character of word.
capwords
capwords(s)
Capitalizes each word in the string s.
expandtabs
expandtabs(s[, tabsize])
Replaces every tab in the string s with one or more spaces, so as to align the final space with the nearest largest multiple of tabsize.
find
find(s, sub[, start[,end]])
Returns the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Returns -1 on failure.
rfind
rfind(s, sub[, start[,end]])
Similar to find, but returns the highest index.
index
index(s, sub[, start[,end]])
Similar to find, but raises ValueError when the substring is not found.
rindex
rindex(s, sub[, start[,end]])
Similar to rfind, but raises ValueError when the substring is not found.
count
count(s, sub[, start[, end]])
Returns the number of non-overlapping occurences of the substring sub in the string s[start:end].
lower
lower(s)
Returns a copy of s with uppercase characters converted to lowercase.
maketrans
maketrans(from, to)
Returns a translation table suitable for passing to translate() or regex.compile(), that will map each character in from into the character at the same position in to; both arguments must have the same length.
split
split(s[, sep[, maxsplit]])
Returns a list of substrings of the string s separated by the string sep (which is assumed to be whitespace by default). If maxsplit is specified and non-zero, it determines how many splits to make at most. When maxsplits splits are made, the remaining rightmost chunk of s becomes the last element of the returned list.
splitfields
splitfields(s[, sep[, maxsplit]])
Same as split()
join
join(words[, sep])
Concatenate a list or tuple of words with intervening occurrences of sep. The default value for sep is a single space character.
joinfields
joinfields(words[, sep])
Same as join().
lstrip
lstrip(s)
Returns a copy of s without leading whitespace characters.
rstrip
rstrip(s)
Returns a copy of s without trailing whitespace characters.
strip
strip(s)
Returns a copy of s without leading and trailing whitespace characters.
swapcase
swapcase(s)
Returns a copy of s with lower case characters converted to upper case and vice versa.
translate
translate(s, table[, deletechars])
Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal.
upper
upper(s)
Returns a copy of s with lower case characters converted to upper case.
ljust
ljust(s, width)
Returns a string of length max(width,len(s)) in which the string s is respectively left, right, or center-justified.
rjust
rjust(s, width)
center
center(s, width)
zfill
zfill(s, width)
Returns a numeric string of lenght width starting with s and padded with zeros to the right.
replace
replace(s, old, new[, maxsplit])
Return a copy of string s with all occurrences of the substring old replaced by new. If the optional argument maxsplit is given, only the first maxsplit occurrences are replaced.

Mathematical functions

Table 14.9. List of mathematical functions. See Math - mathematical functions for a complete reference.

Function nameSyntaxDescription
acos
acos(x)
Returns the arc cosine of x.
asin
asin(x)
Returns the arc sine of x.
atan
atan(x)
Returns the arc tangent of x.
atan2
atan2(x, y)
Returns the arc tangent of x / y.
ceil
ceil(x)
Returns the ceiling of x as a float.
cos
cos(x)
Returns the cosine of x.
cosh
cosh(x)
Returns the hyperbolic cosine of x.
exp
exp(x)
Returns e to the power x.
fabs
fabs(x)
Returns the absolute value of the floating point number x.
floor
floor(x)
Returns the floor of x as a float.
fmod
fmod(x)
Returns the floating point remainder of the modulus division of x by y.
frexp
frexp(x)
Returns the base-2 mantissa and exponent of x as a pair (m, e), wher m is a float and e is an integer such that x == m*2**e. If x is zero returns (0.0, 0), otherwise 0.5 <= abs(m) < 1.
hypot
hypot(x, y)
Returns sqrt(x*x + y*y).
ldexp
ldexp(x, i)
Returns x * (2**i).
log
log(x)
Returns the natural logarithm of x.
log10
log10(x)
Returns the base-10 logarithm of x.
modf
modf(x)
Returns the integer and fractional parts of x as a pair of floats. Both results have the same sign as x.
pow
pow(x, y)
Returns x**y.
sin
sin(x)
Returns the sine of x.
sinh
sinh(x)
Returns the hyperbolic sine of x.
sqrt
sqrt(x)
Returns the square root of x.
tan
tan(x)
Returns the tangent of x.
tanh
tanh(x)
Returns the hyperbolic tangent of x.

Random functions

Table 14.10. List of random functions. See Random - Generate pseudo-random numbers for a complete reference.

Function nameSyntaxDescription
seed
seed([x])
Initializes the random numebr generator; x can be any (hashable) object. Current system time is used by default.
getstate
getstae()
Returns an object capturing the current state of the random number generator. This object can be later passed as an argument to setstate().
setstate
setstate(state)
Restores the random number generator to the state specified by the argument state.
jumpahead
jumpahead(n)
Changes the internal state of the random number generator in the same way as if random() were called n times.
randrange
randrange([start, ]stop[, step])
Returns a randomly selected integer from range([start, ]stop[, step]).
choice
choice(seq)
Returns a random element from a non-empty sequence seq.
shuffle
shuffle(seq[, rand])
Shuffles the sequence seq. The optional argument rand is a 0-argument function returning a random float in [0, 1); defaults to random().
random
random()
Returns the next floating point number from the interval [0, 1) with the uniform distribution.
uniform
uniform(a, b)
Returns a random real number u such that a <= u < b with the uniform distribution.
betavariate
betavariate(alpha, beta)
Returns a random real number between 0 and 1 with the Beta distribution. The parameters must satisfy the conditions alpha > -1 and beta > -1.
cunifvariate
cunifvariate(mean, arc)
Returns a random real number with the cuniform distribution centered around the mean angle and with the range given by arc. Both arguments are expressed in radians.
gamma
gamma(alpha, beta)
Returns a random real number with the Gamma distribution with the parameters alpha > -1 and beta > 0.
gauss
gauss(mu, sigma)
Returns a random real number with the Gaussian (normal) distribution with the mean mu and standard deviation sigma. Slightly faster than normalvariate() below.
lognormvariate
lognormvariate(mu, sigma)
Returns a random real number with the log-normal distribution, where mu and sigma are respectively the mean and standard deviation of the natural logarithm of this distribution.
normalvariate
normalvariate(mu, sigma)
Returns a random real number with the normal distribution with the mean mu and standard deviation sigma.
vonmisesvariate
vonmisesvariate(mu, kappa)
Returns a random angle with the Von Mises distribution, where mu is the mean angle between 0 and 2*pi and kappa is the concentration parameter. If kappa = 0, the distribution is uniform.
paretovariate
paretovariate(alpha)
Returns a random real number with the Pareto distribution, where alpha is the shape parameter.
weibullvariate
weibullvariate(alpha, beta)
Returns a random real number with the Weibull distribution, where alpha is the scale parameter and beta is the shape parameter.

Date/time objects

Table 14.11. List of date and time objects. See Datetime - Basic date and time types for a complete reference.

Object typeSyntaxDescription
date
date(year, month, day)
Returns a date object
time
time(hour, minute, second, microsecond)
Returns a time object
datetime
datetime(year, month, day,
                                hour, minute, second, microsecond)
Returns a datetime object
timedelta
timedelta(days, seconds, microseconds,
                                milliseconds, minutes, hours, weeks)
Returns a timedelta object

Some basic examples of date and time operations:

Example 14.15. Shifting time and date

date1 = date(2009, 4, 11)
shift1 = timedelta(5,45,600,12,33,7,1)                     # 1 week and 5 days later
print date1 + shift1

date2 = date(2008, 12, 22)
shift2 = timedelta(days = -8)                              # 8 days earlier
print date2 + shift2

date3 = datetime(2009, 4, 21)
shift3 = timedelta(days = 3, weeks = 2, hours = 4)         # 2 weeks and 3 days and 4 hours later
print date3 + shift3
    

Output:

2009-04-23
2008-12-14
2009-05-08 04:00:00
    

Example 14.16. Subtracting times and dates

date1= date(2009, 4, 11)
date2 = date(2008, 11, 18)
print date1 - date2                 # timedelta is output
print (date1 - date2).days          # the difference may be counted in days
    

Output:

144 days, 0:00:00
144
    

Example 14.17. Some additional date functions

print date(2000,2,9).today()                            # today
print date(2009, 4, 11).weekday()                       # the day of a week (0 = Monday, ..., 6 = Sunday)
print date(2009, 9,22).isocalendar()                    # the year, week and weekday
    

Output:

2009-09-22
5.0
(2009, 39.0, 2.0)