Reputation: 19
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
Upvotes: 1
Views: 132
Reputation: 191701
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())))
Keep in mind, this only handles non-negative integers
Upvotes: 1
Reputation: 12154
You can do this without much fancy stuff
s = "495 * 89"
#replace non-digits with spaces, goes into a list of characters
li = [c if c.isdigit() else " " for c in s ]
#join characters back into a string
s_digit_spaces = "".join(li)
#split will separate on space boundaries, multiple spaces count as one
nums = s_digit_spaces.split()
print(nums)
#one-liner:
print ("".join([c if c.isdigit() else " " for c in s ]).split())
['495', '89']
['495', '89']
#and with non-digit number stuff
s = "495.1 * -89"
print ("".join([c if (c.isdigit() or c in ('-',".")) else " " for c in s ]).split())
['495.1', '-89']
Finally, this works too:
print ("".join([c if c in "0123456789+-." else " " for c in s ]).split())
Upvotes: 1
Reputation: 520978
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']
Upvotes: 2