简体   繁体   中英

Extract a float from a string Python

I have a string which looks like this :

'< 5s' or '< 0.5s'

And i'm trying to extract the 'duration' from the string. I already have this :

a = '< 5s'
b = int(list(filter(str.isdigit, a))[0])
print(b)

but if i use '< 0.5s' it returns me 0 . How can i include the , with the number ?

With simple regex:

import re

s = '< 0.5s'
dur = re.search(r'-?\d+(\.\d+)?', s).group()
print(dur)   # 0.5

一个简单的b = float(a[2:-1])应达到目的,如果你确定该字符串总是精确地格式化中所示的例子。

import re
b = re.sub("[^\d\.]", "", a)

You can use regex , maybe something like this:

#!/usr/bin/python3
import re
inp="< 0.5s 5s -12z34 -6.7s"
for i in re.findall("-?\d+\.\d+|-?\d+", inp):
    print(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM