Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Explicit Type Conversion: int(), float(), str()

Practical guide to Python explicit type conversion with int(), float(), and str(), including edge cases and error handling.

~4 min readPython
#Python#type conversion#type casting#data types
Illustration of Python explicit type conversion showing arrows between int, float, and str type boxes.

Python explicit type conversion lets you control how a value changes type by calling built-in functions such as int(), float(), and str(). Unlike implicit conversion, which Python performs automatically in expressions like 3 + 0.5, explicit conversion gives you control over when and how a value changes type. This article covers the most common conversion functions, their behavior, and the edge cases that can trip you up in production code.

Why Explicit Type Conversion Matters

Explicit conversion is necessary when Python cannot infer the correct type or when you need to enforce a specific type for an API, database, or serialization layer. For example, reading a number from a text file gives you a string, and arithmetic operations on that string will fail or produce unexpected results. Explicit conversion also makes your intent clear to other developers, reducing the chance of subtle bugs caused by implicit type coercion.

Using int() for Integer Conversion

The int() function converts a value to an integer. It accepts a number or a string. When given a float, it truncates toward zero:

python
int(3.7) # 3 int(-2.9) # -2

When given a string, the string must represent a valid integer literal, optionally with a sign:

python
int("42") # 42 int("-17") # -17

You can also specify a base for string conversion, which is useful for parsing hexadecimal or binary input:

python
int("ff", 16) # 255 int("1010", 2) # 10

A common mistake is passing a string that contains a decimal point. int("3.14") raises a ValueError because the string is not a valid integer literal. Leading and trailing whitespace around a valid integer literal is accepted, so int(" 42 ") works. Strings with internal spaces or other extra characters, such as int("4 2"), also raise ValueError.

Using float() for Floating-Point Conversion

The float() function converts a value to a floating-point number. It accepts numbers and strings that represent valid float literals:

python
float(3) # 3.0 float("3.14") # 3.14 float("-0.5") # -0.5

It also accepts scientific notation:

python
float("1e3") # 1000.0

Unlike int(), float() does not accept a base argument. It also raises ValueError for malformed strings, such as float("3,14") or float(""). Be aware that converting very large integers to float can lose precision, because floats have limited mantissa bits.

Using str() for String Conversion

The str() function converts any object to its string representation. For most built-in types, this produces a human-readable form:

python
str(42) # "42" str(3.14) # "3.14" str([1, 2, 3]) # "[1, 2, 3]"

For custom classes, str() calls the __str__ method if defined, falling back to __repr__. This is useful for logging and error messages, but be careful when using str() on objects that produce large or complex representations, as it can bloat logs.

Handling Conversion Errors and Edge Cases

Both int() and float() raise ValueError when the input string is not a valid number. They also raise TypeError when the argument type is unsupported, such as passing a list or a custom object without the required conversion protocol.

A robust pattern is to wrap conversions in a try-except block when the input comes from user input or external data:

python
def parse_int(value): try: return int(value) except (ValueError, TypeError): return None

This prevents a single malformed value from crashing the entire program. In performance-sensitive code, catching exceptions is acceptable because conversion failures are rare; the overhead of try-except is negligible when the happy path is the norm.

Performance and Maintainability Considerations

Explicit conversion functions are implemented in C and are fast, but they still involve parsing and allocation. For a single value, the cost is trivial. However, in a loop processing millions of values, the conversion overhead can become noticeable. If you are converting a large list of strings to integers, consider using map(int, values) or a list comprehension, which are both efficient and readable.

From a maintainability perspective, explicit conversion makes data flow explicit. It is easier to debug a pipeline where every type change is visible than one that relies on implicit coercion. It also helps when working with strict type checkers like mypy, because the declared return type of a conversion function is clear.

Choosing the Right Conversion Function

FunctionConverts toCommon use case
int()IntegerParsing whole numbers, indexing, counters
float()FloatDecimal math, scientific data, percentages
str()StringLogging, serialization, user-facing output
bool()BooleanTruthiness checks, flag conversion

bool() is another explicit conversion function, though it is often overlooked. It converts any value to True or False using Python's truthiness rules. For example, bool(0) is False, bool("") is False, and bool([1]) is True. Use it when you need to normalize a value to a boolean for a flag or a condition.

When choosing a conversion function, consider the input domain. int() is strict about string format, while float() is more lenient with scientific notation. If you need to parse user input that may contain commas or currency symbols, you will need to preprocess the string before conversion.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.