Python 从单字字符串中提取数字

Python 从单字字符串中提取数字,python,python-3.x,Python,Python 3.x,在我试图制作的这个程序中,我有一个表达式(比如“I=23mm”或“H=4V”),我试图从中提取23(或4),这样我就可以把它转换成一个整数 我一直遇到的问题是,因为我试图从中提取数字的表达式是一个单词,所以我不能使用split()或任何东西 一个我看到但不起作用的例子是- I="I=2.7A" [int(s) for s in I.split() if s.isdigit()] 这不起作用,因为它只需要用空格分隔数字。如果单词int078vert中有一个数字,它就不会提取它。而且,我的也没有空

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

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

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

I="I=2.7A"
[int(s) for s in I.split() if s.isdigit()]
这不起作用,因为它只需要用空格分隔数字。如果单词int078vert中有一个数字,它就不会提取它。而且,我的也没有空间来划定

我试过一个像这样的

re.findall("\d+.\d+", "Amps= 1.4 I")
但它也不起作用,因为传递的数字并不总是两位数。可能是5,或者13.6

我需要编写什么代码,以便在传递字符串时,例如

I="I=2.4A"


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

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

>>> 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'


好消息是
split()
可以接受参数。试试这个:

extracted = float("".join(i for i in I.split("=")[1] if i.isdigit() or i == "."))
顺便说一句,以下是您提供的RE的明细:

"\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

看起来您正在尝试解决整数和十进制数的问题。每个字符串总是有一个数字吗?是的。每个字符串始终有一个数字,但可能有多个小数组成该数字。您的拆分解决方案非常简洁:D.+1欣赏不同的方法+1.
"\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