如何从Python字符串中获取整数值?
在本文中,我们将了解如何从Python字符串中获取整数值。
第一种方法是使用 filter() 方法。我们将字符串和 isdigit() 方法传递给filter方法。Python有一个内置函数叫做 Filter() 。可迭代的对象,如列表或字典,可以将filter函数应用于它,以创建一个新迭代器。根据您提供的标准,此新迭代器可以很好地过滤特定元素。
filter() 方法检查字符串中的数字,并过滤掉满足条件isdigit()的字符。我们需要将结果输出转换为整数。
阅读更多:Python 教程
示例
在下面给出的示例中,我们输入一个字符串,并使用 filter() 和 isdigit() 方法找出其中的整数。 −
str1 = "There are 20 teams competing in the Premier League"
print("给定的字符串是")
print(str1)
print("字符串中的数字是")
print(int(filter(str.isdigit(), str1)))
输出
上面示例的输出如下所示 –
给定的字符串是
There are 20 teams competing in the Premier League
字符串中的数字是
20
使用正则表达式
第二种方法使用了正则表达式。导入re库并安装它(如果尚未安装)以使用它。在导入re库之后,我们可以使用正则表达式“ d+ ”来识别数字。字符串和正则表达式“ d+ ”将作为输入发送到 re.findall() 函数,该函数将返回提供的字符串中包含的所有数字的列表。
示例
在下面给出的示例中,我们输入一个字符串,并使用正则表达式找出其中的整数。
import re
str1 = "There are 21 oranges, 13 apples and 18 Bananas in the basket"
print("给定的字符串是")
print(str1)
print("字符串中的数字是")
print(list(map(int, re.findall('\d+', str1))))
输出
上面示例的输出如下所示 –
给定的字符串是
There are 21 oranges, 13 apples and 18 Bananas in the basket
字符串中的数字是
[21, 13, 18]
使用split()方法
第三种方法是使用 split() 、 append() 和 isdigit() 方法。首先,我们将使用 split() 方法将字符串分割成单词,然后我们将使用 isdigit() 方法检查每个元素是否为数字,如果元素是数字,则使用 append() 方法将该元素添加到一个新列表中。
示例
在下面给出的示例中,我们输入一个字符串,并使用 split() 方法找出其中的数字。 −
str1 = "There are 21 oranges, 13 apples and 18 Bananas in the basket"
print("给定的字符串是")
print(str1)
print("字符串中的数字是")
res = []
for i in str1.split():
if i.isdigit():
res.append(i)
print(res)
输出
上面示例的输出如下所示 –
给定的字符串是
There are 21 oranges, 13 apples and 18 Bananas in the basket
字符串中的数字是
['21', '13', '18']