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

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']

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程