📜  Python – 从字符串中提取百分比(1)

📅  最后修改于: 2023-12-03 15:34:07.459000             🧑  作者: Mango

Python - 从字符串中提取百分比

在数据分析和数据科学领域,我们经常需要从字符串中提取数字和百分比数据。在本篇文章中,我们将讨论如何使用 Python 从字符串中提取百分比。

步骤
  1. 导入 re 模块

首先,我们需要导入 python 中的 re 模块,它是一个正则表达式模块,可以帮助我们从字符串中提取所需的数据。

import re
  1. 创建一个字符串

接下来,我们将创建一个包含百分比数据的字符串。

string = "The percentage of students who passed the exam is 90.5%."
  1. 使用正则表达式提取百分比

下面是一个使用正则表达式从字符串中提取百分比的示例代码。

result = re.search(r'\d+\.\d+%', string)
percentage = result.group()
print(percentage)

在上面的代码中,我们使用正则表达式 \d+.\d+% 来查找包括一个或多个数字,一个小数点和一个百分号的字符串。re.search 函数返回第一个匹配项。最后,我们使用 group 函数获取匹配项。

如果要从字符串中提取多个百分比,我们可以使用 re.findall 函数。

string = "The percentage of students who passed the exam is 90.5%. The percentage of students who failed the exam is 9.5%."
percentages = re.findall(r'\d+\.\d+%', string)
for percentage in percentages:
    print(percentage)

在上面的代码中,我们使用 re.findall 函数从字符串中查找所有匹配项,并将它们打印出来。

总结

本篇文章介绍了如何使用 Python 从字符串中提取百分比。我们使用了 re 模块和正则表达式来实现这个功能。通过仔细的阅读和实践,您已经掌握了从字符串中提取百分比的方法,可以在您的数据分析和数据科学项目中使用。