1

I wish to normalize the integers within a string. Example:

string = ["There is a discount of 45% on the sales in the shopping mall", "60percent discount will be given to any purchase made"]

I am wondering whether will this be possible to do.

a = []
for x in string:
    xsplit = x.split()
    for xx in xsplit:
        if xx.isdigit():
            newxx = xx/100
            a.append(newxx)

My above codes are very expensive and too many loops. I wish to find a way to achieve my expected output while also stay shorter codes. Is that even possible? I will keep updating my new test codes here. Please do assist me.

I received error:

unsupported operand type(s) for /: 'str' and 'int'

My expected output should be:

[0.45, 0.6]

1 Answers1

3

Use re.findall:

import re
res = []
for s in string:
    res.extend(re.findall('\d+', s))
res = [int(r)/100 for r in res]

Output:

[0.45, 0.6]
Chris
  • 29,127
  • 3
  • 28
  • 51