Python int() Function
int()It is one of the most commonly used built-in functions in Python, used to convert data of other types to integer type.
In programming, we often need to convert data of types such as strings, floating-point numbers, or other types into integers for numerical calculations or comparisons.int()This function can help us easily complete this conversion.
Word Definition: intYesintegerAbbreviation of (integer), representing the integer type.
Basic Syntax and Parameters
int()It is a built-in function that can be called directly without importing any module.
Syntax Format
int(x) int(x, base)
Parameter Description
- Parameter x:
- Type: String, number, or other object convertible to an integer
- Description: The value to convert to an integer. If x is a string, the base can be specified in the base parameter.
- Parameter base(Optional):
- Type: Integer (2, 8, 10, 16)
- Description: The base of x, defaulting to 10 (decimal). Only valid when x is a string.
Function Description
- Return Value: Returns an integer object.
- Special Cases:
int()Returns 0 when called without arguments- Floating-point numbers are rounded down (truncated toward zero)
- The string must be a valid numeric representation
Examples
Let us, through a series of examples from simple to complex, thoroughly masterint()the usage of int().
Example 1: Basic Usage - Converting Numbers
Examples
print(int(3.7)) # Output: 3
print(int(-3.7)) # Output: -3
# Convert from boolean value
print(int(True)) # Output: 1
print(int(False)) # Output: 0
# Convert from string
print(int("42")) # Output: 42
print(int(" 10 ")) # Output: 10 (whitespace automatically removed)
Expected output:
3 -3 1 0 42 10
Code analysis:
- When a floating-point number is converted to an integer, the decimal part is truncated directly (rounded toward zero), rather than rounded to the nearest integer.
- Boolean values
TrueTrue converts to 1, andFalseFalse converts to 0. - When converting a string, leading and trailing whitespace characters are automatically removed.
Example 2: Base Conversion
int()It supports converting strings in different bases to decimal integers.
Examples
print(int("1010", 2)) # Output: 10
# Octal string (starting with 0o)
print(int("12", 8)) # Output: 10
# Hexadecimal string (starting with 0x)
print(int("a", 16)) # Output: 10
print(int("FF", 16)) # Output: 255
# String with prefix
print(int("0b1010", 2)) # Output: 10
print(int("0o12", 8)) # Output: 10
print(int("0xff", 16)) # Output: 255
Expected output:
10 10 10 255 10 10 255
Code analysis:
- The second parameter specifies the numeric base of the string: 2 means binary, 8 means octal, and 16 means hexadecimal.
- The string can have a prefix (such as
0b,0o,0x), or it can be without one. - In hexadecimal, a-f can be uppercase or lowercase.
Example 3: Common Application Scenarios
int()It has many application scenarios in actual programming, such as user input processing, data cleaning, and so on.
Examples
# Assume the user entered "100"
user_input = "100"
price = int(user_input)
print(f"Product price: {price} yuan") # Output: Product price: 100 yuan
# Numeric strings read from a file
numbers_str = ["10", "20", "30"]
numbers = [int(n) for n in numbers_str]
print(numbers) # Output: [10, 20, 30]
# Calculate the total
total = sum(numbers)
print(f"Total: {total}") # Output: Total: 60
# Handle a string with decimals (convert to float first, then to int)
price_str = "19.99"
price = int(float(price_str))
print(f"Price (rounded): {price} yuan") # Output: Price (rounded): 19 yuan
Expected output:
商品价格: 100 元 [10, 20, 30] 总和: 60 价格(取整): 19 元
This example demonstratesint()the common usage of int() in practical applications, including handling user input, batch data conversion, and so on.
Other Extensions
Python3 Built-in Functions