Filter out numbers from text using list comprehension

Viewed 60

I have a small text with currency values. I would like to save only the values without the currency signs in a list. Here is my working example so far

Text = "Out of an estimated $5 million budget, $3 million is channeled to program XX, $1 million to program YY and the remainder to program ZZ"

amount = [x for x in Text.split() if x.startswith('$')]

Current code saves the values (with currency sign). How do i strip the values of the dollar sign?

4 Answers

Try this

Text = "Out of an estimated $5 million budget, $3 million is channeled to program XX, $1 million to program YY and the remainder to program ZZ"
# slice $ sign off of each string
amount = [x[1:] for x in Text.split() if x.startswith('$')]
amount
['5', '3', '1']

Using regexes:

import re

re.findall(r"\$(\d+)", s)

use this to strip first character from the list

amount = [x[1:] for x in Text.split() if x.startswith('$')]
amount = [x.replace('$','') for x in Text.split() if x.startswith('$')]
Related