Home > Back-end >  Extraction of Numbers from String
Extraction of Numbers from String

Time:10-08

I am trying to extract numbers from a string. Without any fancy inports like regex and for or if statements.

Example 495 * 89

Output 495 89

Edit I have tried this:

num1 = int(''.join(filter(str.isdigit, num)))

It works, but doesn't space out the numbers

CodePudding user response:

Actually, regex is a very simple and viable option here:

inp = "495   *  89"
nums = re.findall(r'\d (?:\.\d )?', inp)
print(nums)  # ['495', '89']

Assuming you always expect integers and you want to avoid regex, you could use a string split approach with a list comprehension:

inp = "495   *  89"
parts = inp.split()
nums = [x for x in parts if x.isdigit()]
print(nums)  # ['495', '89']

CodePudding user response:

You're close.

You don't want to int() a single value when there are multiple numbers in the string. The filter function is being applied over characters, since strings are iterable that way

Instead, you need to first split the string into its individual tokens, then filter whole numerical strings, then cast each element

s = "123 * 54"
digits = list(map(int, filter(str.isdigit, s.split()))) 
  • Related