Python int() 函数用于将给定值转换为整数。它可以将各种类型的数据(例如数字字符串或浮点数)转换为整数。
如果给定的值是浮点数,则 int() 函数会截断小数部分,返回整数。此外,它还可以与第二个参数一起使用,以指定将数字从二进制、八进制或十六进制表示形式转换为十进制整数的基数。
语法
以下是 Python int() 函数的语法 -
int(x [,base])
参数
此函数采用两个参数,如下所示 -
- x −它表示要转换为整数的值。
- base (可选) −它指定给定数字的基数;默认值为 10,它将 “x” 作为该基数中的字符串进行转换。
返回值
此函数返回一个整数对象。
示例 1以下是 Python int() 函数的示例。在这里,我们将字符串 “123” 转换为整数 -
string_num = "123"
integer_num = int(string_num)
print('The integer value obtained is:',integer_num)
输出
以下是上述代码的输出 -
The integer value obtained is: 123
示例 2
在这里,我们使用 int() 函数将浮点数 “7.8” 转换为整数 -
float_num = 7.8
int_num = int(float_num)
print('The corresponding integer value obtained is:',int_num)
输出
我们可以在下面的输出中看到小数部分被截断了 -
The corresponding integer value obtained is: 7
示例 3
如果你将包含非数字字符的字符串传递给 int() 函数,它将引发 ValueError。
在这里,我们将字符串 “42 apples” 转换为整数 -
# Example with Error
mixed_string = "42 apples"
number_part = int(mixed_string)
print(number_part)
输出
我们可以在下面的输出中看到,由于字符串包含非数字字符 (' apples'),导致转换过程中出现 ValueError -
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
number_part = int(mixed_string)
ValueError: invalid literal for int() with base 10: '42 apples'
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
number_part = int(mixed_string)
ValueError: invalid literal for int() with base 10: '42 apples'
示例 4
现在,我们处理一个同时包含数字和非数字字符的字符串。
首先,我们只从 “mixed_string” 中提取数字字符。我们使用列表推导式创建 “numeric_part” 变量,该推导式过滤掉非数字字符,从而生成仅包含数字 “42” 的字符串。最后,我们使用 int() 函数将此字符串转换为整数 -
# Example without Error
mixed_string = "42 apples"
numeric_part = ''.join(char for char in mixed_string if char.isdigit())
number_part = int(numeric_part)
print('The integer value obtained is:',number_part)
输出
生成的结果如下 -
The integer value obtained is: 42