Python How to Convert Data Types Easily
int() to convert to integer, float() for floating-point numbers, str() for strings, and bool() for boolean values.Examples
How to Think About It
int() for whole numbers or str() for text. These functions take your original value and change it to the new type if possible.Algorithm
Code
value_str = "123" value_int = int(value_str) value_float = float(value_int) value_bool = bool(value_int) value_str_again = str(value_bool) print(value_int) print(value_float) print(value_bool) print(value_str_again)
Dry Run
Let's trace converting the string "123" to int, then float, then bool, then back to string.
Convert string to int
value_str = "123" -> int(value_str) = 123
Convert int to float
value_int = 123 -> float(value_int) = 123.0
Convert int to bool
value_int = 123 -> bool(value_int) = True
| Step | Value | Type |
|---|---|---|
| Initial | "123" | str |
| After int() | 123 | int |
| After float() | 123.0 | float |
| After bool() | True | bool |
Why This Works
Step 1: Using int() to convert to integer
The int() function takes a string or number and converts it to an integer if possible.
Step 2: Using float() to convert to decimal number
The float() function converts integers or strings to floating-point numbers.
Step 3: Using bool() to convert to boolean
The bool() function converts values to True or False, where zero or empty values become False.
Step 4: Using str() to convert to string
The str() function converts any value to its string representation.
Alternative Approaches
value = "123" converted = eval(value) # Converts string '123' to int 123 print(converted)
import ast value = "123" converted = ast.literal_eval(value) # Safely converts string to int print(converted)
Complexity: O(1) time, O(1) space
Time Complexity
Conversion functions like int(), float(), str(), and bool() run in constant time because they process a single value without loops.
Space Complexity
These functions use constant extra space since they create a new value of the target type without additional data structures.
Which Approach is Fastest?
Built-in functions like int() and float() are fastest and safest; eval() is slower and risky, while ast.literal_eval() is safer but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| int()/float()/str()/bool() | O(1) | O(1) | Simple, safe type conversion |
| eval() | O(1) | O(1) | Dynamic but unsafe conversion |
| ast.literal_eval() | O(1) | O(1) | Safe evaluation of literals |