使用Python正则表达式查找字符串中的所有数字
从文本中提取数字是Python数据分析中非常常见的要求。使用Python正则表达式库可以轻松实现。这个库帮助我们定义可以提取为子字符串的数字模式。
示例
在下面的示例中,我们使用re模块中的findall()函数。该函数的参数是我们想要提取的模式以及我们想要从中提取的字符串。请注意,下面的示例只获取数字,而不获取小数点或负号。
import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list = re.findall(r'\d+', str)
print(num_list)输出
运行以上代码得到以下结果:
Enter a String with numbers: Go to 13.8 miles and then -4.112 miles. ['13', '8', '4', '112']
捕获小数点和符号
我们可以扩展搜索模式,在搜索结果中包含小数点和负号或正号。
示例
import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list=re.findall(r'[-+]?[.]?[\d]+',str)
print(num_list)输出
运行以上代码得到以下结果:
Enter a String with numbers: Go to 13.8 miles and then -4.112 miles. ['13', '.8', '-4', '.112']
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP