M.B
M.B

Reputation: 19

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?

Upvotes: 1

Views: 205

Answers (4)

tafer
tafer

Reputation: 79

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

Upvotes: 1

Garvit Kothari
Garvit Kothari

Reputation: 21

use this to strip first character from the list

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

Upvotes: 1

cottontail
cottontail

Reputation: 23449

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

Upvotes: 2

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27271

Using regexes:

import re

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

Upvotes: 1

Related Questions