In Python programming, we often need to handle different types of data, such as numbers entered by users, text read from files, etc. These data may be presented in different types, and sometimes we need to convert them to another type for calculation or processing. This is where variable type conversion comes in handy. Python provides simple built-in functions to easily convert between int (integers), str (strings), and float (floating-point numbers).
I. Review of Common Basic Types¶
Let’s review the three most fundamental data types:
- int (Integer) : Numbers without a decimal point, e.g., 123, -456.
- str (String) : A sequence of characters enclosed in single or double quotes, e.g., "hello", '123'.
- float (Floating-Point Number) : Numbers with a decimal point, e.g., 3.14, -0.5.
II. Methods for Converting int Types¶
1. int to str¶
Use the str() function to convert an integer to a string. The number will become a sequence of characters after conversion.
Example :
a = 100 # Define an integer variable
b = str(a) # Convert integer to string
print(b) # Output: '100'
print(type(b)) # Output: <class 'str'> # Verify the type has changed to string
2. int to float¶
Use the float() function to convert an integer to a float (the integer will automatically add a decimal point and .0).
Example :
a = 5 # Integer variable
b = float(a) # Convert to float
print(b) # Output: 5.0
print(type(b)) # Output: <class 'float'>
III. Methods for Converting str Types¶
1. str to int¶
Use the int() function to convert a string to an integer, but the string must be a pure number (without decimals or letters), otherwise an error will occur.
Correct Example :
str_num = "123" # Pure numeric string
int_num = int(str_num) # Convert to integer
print(int_num) # Output: 123
print(type(int_num)) # Output: <class 'int'>
Incorrect Example (Conversion Fails):
str_num = "12.3" # Contains a decimal point, cannot convert to int
int_num = int(str_num) # Error: ValueError: invalid literal for int() with base 10: '12.3'
str_num = "abc" # Contains letters, cannot convert to int
int_num = int(str_num) # Error: ValueError: invalid literal for int() with base 10: 'abc'
2. str to float¶
Use the float() function to convert a string to a float. The string can be a pure integer (e.g., "123") or a number with a decimal point (e.g., "12.3").
Example :
str_num1 = "456"
float_num1 = float(str_num1)
print(float_num1) # Output: 456.0
str_num2 = "78.9"
float_num2 = float(str_num2)
print(float_num2) # Output: 78.9
IV. Methods for Converting float Types¶
1. float to int¶
Use the int() function to convert a float to an integer, but the decimal part will be directly truncated (not rounded).
Example :
a = 3.9 # Floating-point number
b = int(a) # Truncate the decimal part
print(b) # Output: 3
a = 5.0 # Floating-point number in integer form
b = int(a)
print(b) # Output: 5
2. float to str¶
Use the str() function to convert a float to a string, preserving the original numeric form (including the decimal point).
Example :
a = 6.28 # Floating-point number
b = str(a) # Convert to string
print(b) # Output: '6.28'
print(type(b)) # Output: <class 'str'>
V. Common Questions and Notes¶
-
Reasons for Conversion Failure: If the string contains non-numeric characters (e.g., letters, special symbols), conversion will throw a
ValueError. For example,int("12a3")orfloat("abc")will both error out. -
Pre-Conversion Check: If you’re unsure if a string can be safely converted, use
try-exceptto catch errors and avoid program crashes.
Example (Error Handling) :
str_num = "12.3"
try:
int_num = int(str_num)
print("Conversion successful:", int_num)
except ValueError:
print("Conversion failed! The string cannot be converted to an integer")
# Output: Conversion failed! The string cannot be converted to an integer
VI. Summary¶
Python type conversion is implemented through three built-in functions: int(), str(), and float(). The core conversion rules are:
- int ↔ str: The string must be a pure number (converting int to str is simple and risk-free).
- str → float: The string can contain a decimal point, making it more flexible.
- float → int: The decimal part will be truncated; be aware if the result meets expectations.
By practicing different conversion scenarios (e.g., user input handling, numeric calculations), you can master these basic techniques and avoid errors caused by type mismatches.