Lokesh Gurjar
Lokesh Gurjar

Reputation: 39

Can we extract number from string and multiply them

I am trying to make a program that can extract all numbers from string and multiply them like string is "multiply 30 and 50", then program should able to remove spaces and alphabets and multiply remaining numbers, numbers can be more then 2, can you please tell me how can i do it

test = '*'.join(c for c in "multiply 30 and 50" if c.isdigit())
print(f'answer is {test}') 

The result should be 1500

Upvotes: 3

Views: 401

Answers (2)

tonypdmtr
tonypdmtr

Reputation: 3235

Similar to your attempted approach, but working:

s = 'multiply 5 by 10'
import re
s = '*'.join(re.findall('\d+',s))
print(f'{eval(s)}')

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

You can use a regex for this:

from re import compile as recompile

numbers = recompile(r'\d+')

You can then use reduce and mul to multiply the digits, like:

from functools import reduce
from operator import mul

query = 'multiply 30 and 50'
result = reduce(mul, map(int, numbers.findall(query)))

This then gives us:

>>> result
1500

This of course does not take into acount the "multiply ... and ..." part, so if it was "subtract 5 from 10", it would still return 50.

If you want to make a more advanced system, that thus does not just looks for numbers in the string, you should implement a parser [wiki], for example with a compiler-compiler [wiki].

Upvotes: 1

Related Questions