Cast

Contents

Cast#

Constructors double as casts. Each raises ValueError (or TypeError) on bad input, so wrap user-supplied data in try / except at the boundary.

int("42")                 # 42
int("0xff", 16)           # 255
float("3.14")             # 3.14
str(42)                   # "42"
list("abc")               # ['a', 'b', 'c']
tuple([1, 2, 3])          # (1, 2, 3)
set([1, 1, 2])            # {1, 2}
dict([("a", 1), ("b", 2)])
bytes("hi", "utf-8")      # b'hi'
bool("")                  # False (empty string is falsy)
bool("False")             # True (non-empty string is truthy)

bool follows the truthiness rules in bool; in particular bool("False") is True because the string is non-empty. Use a dedicated parser (json.loads, distutils.util.strtobool, a hand-rolled mapping) for string-to-bool from a config or CLI.

For exact-decimal casting use decimal.Decimal, for fractions use fractions.Fraction.

from decimal import Decimal
from fractions import Fraction

Decimal("0.1")            # exact
Fraction(1, 3)            # 1/3 exact

References#