如何在Python中从字符串中获取整数值?


在本文中,我们将了解如何在Python中从字符串中获取整数值。

第一种方法是使用filter()方法。我们将字符串和isdigit()方法传递给filter方法。Python有一个内置函数叫做filter()。像列表或字典这样的可迭代对象可以应用filter函数来创建一个新的迭代器。根据您提供的条件,这个新的迭代器可以很好地过滤掉特定的元素。

filter()方法检查字符串中的数字,并过滤掉满足isdigit()条件的字符。我们需要将结果输出转换为int才能获得整数输出。

示例

在下面的示例中,我们以字符串作为输入,并使用filter()isdigit()方法查找字符串中存在的整数

str1 = "There are 20 teams competing in the Premier League"

print("The given string is")
print(str1)

print("The number present in the string is")
print(int(filter(str.isdigit(), str1)))

输出

上面示例的输出如下所示:

The given string is
There are 20 teams competing in the Premier League
The number present in the string is
20

使用正则表达式

第二种方法使用正则表达式。要使用它,请导入re库,如果尚未安装,则安装它。导入re库后,我们可以使用正则表达式“\d+”来识别数字。字符串和正则表达式“\d+”将作为输入发送到re.findall()函数,该函数将返回提供的字符串中包含的所有数字的列表。

示例

在下面的示例中,我们以字符串作为输入,并使用正则表达式查找字符串中存在的整数。

import re
str1 = "There are 21 oranges, 13 apples and 18 Bananas in the basket"

print("The given string is")
print(str1)

print("The number present in the string is")
print(list(map(int, re.findall('\d+', str1))))

输出

上面示例的输出如下所示:

The given string is
There are 21 oranges, 13 apples and 18 Bananas in the basket
The number present in the string is
[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("The given string is")
print(str1)

print("The number present in the string is")
res = []
for i in str1.split():
   if i.isdigit():
      res.append(i)
print(res)

输出

上面示例的输出如下所示:

The given string is
There are 21 oranges, 13 apples and 18 Bananas in the basket
The number present in the string is
['21', '13', '18']

更新于:2022年12月7日

11K+ 浏览量

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.