Python Glossary Русский

all Python 3Data typesterm

Type conversion

conversion

Explicit conversion of one type into another with the built-in int(), float(), str() and bool(). A conversion that is not possible raises ValueError or TypeError.

Syntax

int(x) | float(x) | str(x) | bool(x)

bool() is the sneakiest: any non-empty string is truthy, so bool("False") and bool("0") are both True. And int() of a float truncates toward zero (int(-3.9) → -3, not rounding), while int("3.9") raises ValueError outright — a decimal string must go through float() first.

Examples

print(int(3.9))  # → 3 (отбрасывание дробной части)
print(int("42"))  # → 42
print(float(7))  # → 7.0
print(str(100))  # → "100"
print(bool(0))  # → False
print(bool(""))  # → False
try:
    int("3.14")
except ValueError as e:
    print(type(e).__name__)  # → ValueError (нельзя напрямую)
print(int(float("3.14")))  # → 3 (через float)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy