SoFunction
Updated on 2025-05-14

One article teaches you to thoroughly master Python data type conversion

1. The "Law of Interchange" of the four basic data types in Python

The core data types of Python include:int(integer)float (float)str(String)bool (boolean value). Here are the tips for converting them:

String → integer/floating point number

# string to integerage = "25"  
print(int(age))  # Output: 25
# string to floating point numberprice = "99.9"  
print(float(price))  # Output: 99.9
# ⚠️ Big pit warning!  Non-numeric strings will report an errortry:
    age = "twenty-five"
    print(int(age))  # Report an error: ValueError: invalid literal for int() with base 10: 'twenty-five'except ValueError as e:
    print(f"ValueError: {e}")

Skill:usetry-exceptCatch exceptions to avoid program crashes!

Integer/Float Number → String

# Number to string (must be required for splicing and log output)num = 100  
print(str(num) + "%")  # Output: 100%
# Floating point numbers retain two decimal placespi = 3.1415926  
print(f"{pi:.2f}")  # Output: 3.14 (recommended f-string formatting)

"Hidden Rules" for Boolean Values

# Other types → Boolean value (0, empty value will be converted to False!)print(bool(0))      # False  
print(bool(""))     # False  
print(bool([]))     # False  
print(bool("Hi"))   # True  

# Boolean value → integer (True=1, False=0)print(int(True))   # 1  
print(float(False))# 0.0  

"Automatic upgrade" of integers and floating-point numbers

# When integer and floating point operations, the result will be automatically upgraded to floatresult = 5 + 3.14  
print(result)       # 8.14 (type float)
# Explicit conversion priorityprint(float(10))    # 10.0  
print(int(8.88))    # 8 (Direct truncation, non-rounding!)

2. A guide to avoid pits that spread across the Internet!

Pit 1input()The input default is a string, and it must be converted before mathematical calculation!

user_input = input("Please enter the number:")  # Enter "123"result = int(user_input) * 2  
print(result)  # 246  

Pit 2int()When converting floating point numbers, discard the decimals directly, useround()Rounding is more reliable!

print(int(9.99))   # 9  
print(round(9.99)) # 10  

Pit 3bool("False")It turned out to be True! Because non-empty strings are True!

print(bool("False"))  # True (String is not empty)print(bool(0))        # False  

3. Advanced skills: eval() function and implicit conversion

# eval() can parse string expressions, but use them with caution (safety risk)expression = "3 + 4 * 2"  
print(eval(expression))  # 11  

# Implicit conversion: Automatic bool conversion in if conditiondata = []  
if data:  
    print("There is data")  
else:  
    print("Empty list!")  # Output: empty list!

4. Master all conversion relationships in one form

method illustrate
int(x [,base ]) Convert x to an integer
float(x ) Convert x to a floating point number
complex(real [,imag ]) Create a plural
str(x ) Convert object x to string
repr(x ) Convert object x to expression string
eval(str ) Used to calculate valid Python expressions in a string and return an object
tuple(s ) Convert sequence s to a tuple
list(s ) Convert sequence s to a list
chr(x ) Convert an integer to a character
unichr(x ) Convert an integer to Unicode characters
ord(x ) Convert a character to its integer value
hex(x ) Convert an integer to a hexadecimal string
oct(x ) Convert an integer to an octal string

This is the article about this article teaching you to thoroughly master Python data type conversion. For more related Python data type conversion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!