使用Python函数来从字符串中提取数字
发布时间:2023-06-05 17:49:28
以下是使用Python函数从字符串中提取数字的代码:
import re
def extract_numbers(string):
"""
Extracts all numbers from a string and returns them as a list.
"""
numbers = []
pattern = r'\d+'
matches = re.findall(pattern, string)
for match in matches:
numbers.append(int(match))
return numbers
此函数使用Python的re模块来执行正则表达式匹配。它搜索并提取所有数字并返回它们的列表。
正则表达式模式'\d+'匹配一个或多个数字。findall()函数查找字符串中的所有匹配项并返回一个列表。然后将每个匹配项转换为整数并添加到一个列表中。
以下是使用该函数的示例:
string = "The price is $100 and the quantity is 20" numbers = extract_numbers(string) print(numbers) # Output: [100, 20]
