如何在Python中提取字符串中的数字?
Python中有多种方法可以从字符串中提取数字。一种方法是使用正则表达式。正则表达式是用于匹配和操作字符串的模式。这是一个使用正则表达式从字符串中提取所有数字的示例代码片段。
使用re.findall()函数
示例
在这个例子中,我们使用re.findall()函数搜索文本字符串中所有数字的出现。正则表达式\d+\.\d+|\d+匹配浮点数和整数。
import re
text = "The price of the book is $29.99"
numbers = re.findall('\d+\.\d+|\d+', text)
print(numbers)
输出
['29.99']
使用isdigit()方法
另一种从字符串中提取数字的方法是使用isdigit()方法,如果字符串中的所有字符都是数字,则返回True。
示例
在这个例子中,我们使用split()方法将文本字符串分割成一个单词列表。然后,我们遍历每个单词,并使用isdigit()方法检查它是否是数字。如果是,则将其转换为整数后添加到numbers列表中。
text = "There are 10 apples in the basket"
numbers = []
for word in text.split():
if word.isdigit():
numbers.append(int(word))
print(numbers)
输出
[10]
使用正则表达式
您可以使用Python中的re模块使用正则表达式从字符串中提取数字。这是一个例子
示例
此代码将输出出现在字符串中的数字列表:[3, 1, 2, 3]。正则表达式'\d+'匹配字符串中一个或多个数字。
import re
string = "There are 3 numbers in this string: 1, 2, and 3."
numbers = re.findall('\d+', string)
print(numbers)
输出
['3', '1', '2', '3']
使用循环和isdigit()方法
您可以循环遍历字符串中的每个字符,并使用isdigit()方法检查它是否是数字。
示例
string = "There are 3 numbers in this string: 1, 2, and 3."
numbers = []
current_number = ""
for char in string:
if char.isdigit():
current_number += char
elif current_number:
numbers.append(int(current_number))
current_number = ""
if current_number:
numbers.append(int(current_number))
print(numbers)
输出
[3, 1, 2, 3]
使用split()和isdigit()方法
如果数字由非数字字符分隔,您可以使用这些字符分割字符串,然后检查每个生成的子字符串是否为数字。
示例
string = "There are 3 numbers in this string: 1, 2, and 3."
numbers = []
for substring in string.split():
if substring.isdigit():
numbers.append(int(substring))
print(numbers)
输出
[3]
使用isnumeric()方法和for循环
示例
此代码创建一个名为numbers的空列表,然后将输入字符串分割成一个单词列表。然后,它循环遍历列表中的每个单词,并使用isnumeric()方法检查它是否为数字。如果它是一个数字,它将被添加到numbers列表中。最后,打印numbers列表。
my_string = "I have 2 apples and 3 oranges"
numbers = []
for word in my_string.split():
if word.isnumeric():
numbers.append(int(word))
print(numbers)
输出
[2, 3]
使用re.findall()函数
示例
此代码导入re模块,并使用re.findall()函数查找输入字符串中所有数字的实例。然后,使用列表推导式将生成的数字字符串列表转换为整数列表。最后,打印numbers列表。
import re my_string = "I have 2 apples and 3 oranges" numbers = [int(num) for num in re.findall(r'\d+', my_string)] print(numbers)
输出
[2, 3]
使用生成器表达式和map()函数
示例
此代码使用生成器表达式和map()函数创建一个整数列表。生成器表达式循环遍历输入字符串中的每个单词,并且只返回使用isdigit()方法的数字。map()函数将int()函数应用于每个数字字符串,将其转换为整数。最后,打印生成的整数列表。
my_string = "I have 2 apples and 3 oranges" numbers = list(map(int, (word for word in my_string.split() if word.isdigit()))) print(numbers)
输出
[2, 3]
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP