4.1 The int() Function
In Python, type conversion (also called type casting) lets you convert values from one data type to another. We've briefly touched on converting a string to a number during input, but now let's dive deeper into this topic. Let's check out the three main functions for type conversion: int(), str(), and float().
The int() function is used to convert a value to an integer.
Converting a string to an integer:
num_str = "42"
num_int = int(num_str)
print(num_int) # Output: 42
You'll get an error if the string isn't a number:
num_str = "forty two"
num_int = int(num_str)
print(num_int) # ValueError: invalid literal for int() with base 10: 'forty two'
Converting a floating-point number to an integer:
num_float = 42.9
num_int = int(num_float)
print(num_int) # Output: 42
Rounding down always happens in such conversions — only the integer part of the number is kept. For example, 1.9999 will give 1.
Converting a boolean value to an integer:
A true value (True) is often called a "logical one," and a false value (False) is a "logical zero." After conversion, they become regular one and zero respectively.
true_bool = True
false_bool = False
print(int(true_bool)) # Output: 1
print(int(false_bool)) # Output: 0
4.2 The str() Function
The str() function is used to convert values to strings. Pretty much anything can be converted into a string.
Converting an integer to a string:
num_int = 42
num_str = str(num_int)
print(num_str) # Output: "42"
Converting a floating-point number to a string:
num_float = 42.9
num_str = str(num_float)
print(num_str) # Output: "42.9"
Converting a boolean value to a string:
true_bool = True
false_bool = False
print(str(true_bool)) # Output: "True"
print(str(false_bool)) # Output: "False"
4.3 The float() Function
The float() function is used to convert a value to a floating-point number (a decimal number).
Converting a string to a floating-point number:
num_str = "42.9"
num_float = float(num_str)
print(num_float) # Output: 42.9
Converting an integer to a floating-point number:
num_int = 42
num_float = float(num_int)
print(num_float) # Output: 42.0
Converting a boolean value to a floating-point number:
true_bool = True
false_bool = False
print(float(true_bool)) # Output: 1.0
print(float(false_bool)) # Output: 0.0
GO TO FULL VERSION