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.

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:
int(3.7) # 3
int(-2.9) # -2When given a string, the string must represent a valid integer literal, optionally with a sign:
int("42") # 42
int("-17") # -17You can also specify a base for string conversion, which is useful for parsing hexadecimal or binary input:
int("ff", 16) # 255
int("1010", 2) # 10A 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:
float(3) # 3.0
float("3.14") # 3.14
float("-0.5") # -0.5It also accepts scientific notation:
float("1e3") # 1000.0Unlike 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:
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:
def parse_int(value):
try:
return int(value)
except (ValueError, TypeError):
return NoneThis 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
| Function | Converts to | Common use case |
|---|---|---|
int() | Integer | Parsing whole numbers, indexing, counters |
float() | Float | Decimal math, scientific data, percentages |
str() | String | Logging, serialization, user-facing output |
bool() | Boolean | Truthiness 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 toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.