
34
|
Python Pocket Reference
A Context object in this module allows for specifying preci-
sion (number of decimal digits) and rounding modes (down,
ceiling, etc.):
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.1428571428571428571428571429")
>>> decimal.getcontext().prec = 4
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.1429")
Type Conversions
Tables 10 and 11 define common built-in tools for convert-
ing from one type to another.
Table 10. Sequence converters
Converter Converts from Converts to
list(X) map(None, X)
[n for n in X]
a
a
The list comprehension form is much slower than list(), and list() has
made this form of map(None, ...) obsolete since Version 2.2.
String, tuple, user-defined
sequence, any iterable
List
tuple(X) String, list, user-defined sequence,
any iterable
Tuple
''.join(X) Sequence of strings String
Table 11. String/object converters
Converter Converts from Converts to
eval(S) String Any object with a syntax
(expression)
int(S [, base])
a
float(S)
long(S [, base])
String or number Integer, float, long
repr(X)
str(X)
`X`
(back quotes)
Any Python object String (
repr is as code,
str is user-friendly, back
quotes yield the same as
repr)
X%Y (string formatting) Objects with format codes String