从1字符串中提取数字

2024-06-02 23:31:03 发布

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

在这个程序中,我有一个表达式(例如“I=23mm”或“H=4V”),我试图从中提取23(或4),这样我就可以把它变成一个整数。在

我一直遇到的问题是,由于我试图从中提取数字的表达式是1个单词,所以我不能使用split()或任何东西。在

我看到但不起作用的一个例子是-

I="I=2.7A"
[int(s) for s in I.split() if s.isdigit()]

这是行不通的,因为它只接受用空格分隔的数字。如果单词int078vert中有一个数字,它不会提取它。而且,我的也没有空间来划分。在

我试过这个样子的

^{pr2}$

但它也不起作用,因为传递的数字并不总是2位数。可能是5,或者13.6。在

如果我传递一个字符串,比如

I="I=2.4A"

或者

I="A=3V"

所以我只能从这个字符串中提取数字?(并对其进行操作)?没有空格或其他常量字符可以用来分隔。在


Tags: 字符串in程序forif表达式数字整数
2条回答
>>> import re
>>> I = "I=2.7A"
>>> s = re.search(r"\d+(\.\d+)?", I)
>>> s.group(0)
'2.7'
>>> I = "A=3V"
>>> s = re.search(r"\d+(\.\d+)?", I)
>>> s.group(0)
'3'
>>> I = "I=2.723A"
>>> s = re.search(r"\d+(\.\d+)?", I)
>>> s.group(0)
'2.723'

RE可能对这一点有好处,但由于已经发布了一个RE答案,我将以您的非正则表达式为例进行修改:


One example I saw but wouldnt work was - 

I="I=2.7A"
[int(s) for s in I.split() if s.isdigit()]

好在split()可以接受参数。试试这个:

^{pr2}$

顺便说一句,这是你们提供的稀土的明细表:

"\d+.\d+"
\d+ #match one or more decimal digits
. #match any character   a lone period is just a wildcard
\d+ #match one or more decimal digits again

一种正确的方法是:

"\d+\.?\d*"
\d+ #match one or more decimal digits
\.? #match 0 or 1 periods (notice how I escaped the period)
\d* #match 0 or more decimal digits

相关问题 更多 >