-1

I have got dosage strength values like 20.5 mg,20 mg in string . I want to extract only integer or float value.

Below is what I have tried so far

def parseint(self,string):
   return int(''.join([x for x in string if x.isdigit()]))   

But this is not working in all cases.

ex1)

parseint('2 mg')
o/p- 2

ex2)

parseint('10.2 mg')
o/p - 102 

Expected output:

i/p "20.5 MG" o/p- 20.5
i/p "20.0 MG" o/p - 20.0
i/p "20.0 MG" o/p - 20.0

3 Answers3

2

Using Regex.

Ex:

import re


def parseint(string):
    m = re.search(r"(\d*\.?\d*)", string)
    return m.group() if m else None

s1 = "20.5 mg,"
s2 = "20 mg"

print(parseint(s1))
print(parseint(s2))

Output:

20.5
20
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0
def parseint(string):
    return float(''.join([x for x in string if x.isdigit() or x == '.']))

Something like this should work.

Ninad Gaikwad
  • 4,272
  • 2
  • 13
  • 23
  • Actually this is working but in one case where values like "25 MG" . it is giving me output like 25.0, but i think i need 25 only . – Rahul Rajpoot Oct 11 '18 at 06:24
0

Using list comprehension, with .split(),float, andint`

res = [float(i.split()[0]) if '.' in i else int(i.split()[0]) for i in lst]

Expanded explanation

lst = ['2 mg', '10.2 mg', '20.5 MG']
for i in lst:
    if '.' in i:
        print(float(i.split()[0]))
    else:
        print(int(i.split()[0]))
# 2
# 10.2
# 20.5
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20