如何在 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.