如何从字符串中提取数字?

2024-05-13 10:19:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子

a=['invoice β invoice # 2018-33167-2 β date 03/21/2018 β total due $8,804.90']  

我只想从表单列表中提取数字

a=['2018-33167-2 03/21/2018 8,804.90']

我用正则表达式来提取

for i in a:
  res = re.sub("\D", "", i)

但结果是

res=201833167203212018880490

Tags: inre表单列表fordateres数字
1条回答
网友
1楼 · 发布于 2024-05-13 10:19:38

根据预期的输出,您需要的不仅仅是数字。数字可以有/-,

也许,你想要的东西是从一个数字开始,又以一个数字结束,但是中间的东西除了一个空间之外?p>
import re
a='invoice β invoice # 2018-33167-2 β date 03/21/2018 β total due $8,804.90'
print(re.findall(r'\d[^ ]+\d', a))

输出

python3 test.py
['2018-33167-2', '03/21/2018', '8,804.90']

相关问题 更多 >