I have a string: string = "2017.5 is halfway through the year"
. Is there a way to extract this "2017.5"
from the string? I tried using string.isdigit()
, but that only worked for non-floats.
Asked
Active
Viewed 2,072 times
1

Marshall Scudder
- 77
- 18
-
float(string.split(' ')[0]) – e4c5 Jun 08 '17 at 05:42
-
`string.split()[0]` – Avinash Raj Jun 08 '17 at 05:43
-
duplicate? https://stackoverflow.com/questions/379906/parse-string-to-float-or-int – GavinBrelstaff Jun 08 '17 at 05:43
3 Answers
2
If your float is always expressed in decimal notation something like
>>> import re
>>> re.findall("\d+\.\d+", "2017.5 is halfway through the year")
['2017.5']
may suffice.
For parse int and float (point separator) values:
re.findall( r'\d+\.*\d*', '2017.5 is halfway through the year' )
result:
['2017.5']

Vignesh Kumar A
- 27,863
- 13
- 63
- 115
1
here is an example using re.match
:
>>> import re
>>> ok = '2017.5 and some stuff'
>>> hmm = re.match(r'[0-9\.]+', ok)
>>> hmm.group()
'2017.5'
r'[0-9\.]+'
is a regex to extract the group that matches numbers and periods

jmunsch
- 22,771
- 11
- 93
- 114
0
just a dirty implementation without regex and with the single digit/float per sentence:
s = "new 2017.5 is halfway through the year1"
def process(all,new):
def is_float_try(str):
try:
float(str)
return True
except ValueError:
return False
return new if new.isdigit() or is_float_try(new) else all
print reduce(process,s.split(),'')
# 2017.5

brc
- 249
- 2
- 6