I would like to extract only the numbers contained in a string. Can isdigit()
and split()
be combined for this purpose or there is simpler/faster way?
Example:
m = ['How to extract only number 122', 'The number 35 must be extracted', '1052 must be extracted']
Output:
numbers = [122, 35, 1052]
text = ['How to extract only number', 'The number must be extracted', 'must be extracted']
My code:
text = []
numbers = []
temp_numbers = []
for i in range(len(m)):
text.append([word for word in m[i].split() if not word.isdigit()])
temp_numbers.append([int(word) for word in m[i].split() if word.isdigit()])
for i in range(len(m)):
text[i] = ' '.join(text[i])
for elem in temp_numbers:
numbers.extend(elem)
print(text)
print(numbers)
==True
and==False
and factor out the commonfor word in m[i].split() if word.isdigit()
but other than that this looks as simple as it can get.