findall() 是 Python 中正则表达式模块 re 的一个函数,用于在字符串中查找所有与正则表达式匹配的子串。它返回一个包含所有匹配项的列表。如果没有找到匹配项,则返回一个空列表。
以下是 findall() 函数的基本用法:
re 模块:import re
pattern = r'\d+'
这里,\d 表示数字,+ 表示匹配一个或多个数字。
re.findall() 函数在字符串中查找所有匹配项:text = "There are 123 apples and 456 oranges in the basket."
matches = re.findall(pattern, text)
print(matches) # 输出:['123', '456']
注意,findall() 返回的结果是字符串列表。如果需要将结果转换为整数列表,可以使用列表推导式:
int_matches = [int(match) for match in matches]
print(int_matches) # 输出:[123, 456]
这就是 Python 中 findall() 函数的基本用法。