findall提取字符串中的数字
发布时间:2023-06-26 20:25:02
findall是Python re模块中用于提取匹配的字符串的函数,它可以用于从字符串中提取数字。
例如,我们有一个字符串"Today is 2021-10-19 and the temperature is 25 degrees Celsius.",我们想从中提取出日期和温度的数字。可以使用下面的代码来完成:
import re
string = "Today is 2021-10-19 and the temperature is 25 degrees Celsius."
date_pattern = r"\d{4}-\d{2}-\d{2}"
temperature_pattern = r"\d+"
dates = re.findall(date_pattern, string)
temperatures = re.findall(temperature_pattern, string)
print("Dates:", dates)
print("Temperatures:", temperatures)
以上代码中,我们使用了两个正则表达式模式来匹配日期和温度。其中日期模式为"\d{4}-\d{2}-\d{2}",可以匹配类似"2021-10-19"的日期,温度模式为"\d+",可以匹配任意数字。
然后,使用re.findall函数,我们可以从字符串中提取出所有匹配模式的字符串,并返回一个列表。最后我们输出了提取出的日期和温度列表。
输出结果为:
Dates: ['2021-10-19'] Temperatures: ['25']
可以看到,我们成功地从字符串中提取出了日期和温度的数字。
总结一下,使用Python中的re模块和findall函数可以很方便地从字符串中提取出需要的信息,是数据处理和分析中常用的工具。
