Search code examples
pythonlist-comprehension

Filter out numbers from text using list comprehension


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?


Solution

  • 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']