Python Remove Comma In Dollar Amount

2020-02-10 04:09发布

Using Python v2, I have the user entering an amount into a string as below:

RawPurchaseAmount = raw_input("Please enter purchase amount: ")

PurchaseAmount = float(RawPurchaseAmount.strip().lstrip("$"))

This is stripping out any blank spaces at the front of the input, and removing the $ sign if one is entered.

Is there a way to remove a comma symbol if it is entered? IE: $10,000.00 to become 10000.00

Thanks for any help.

标签: python string
4条回答
别忘想泡老子
2楼-- · 2020-02-10 04:38
>>> x = '$10,00.00'
>>> ''.join(e for e in x if e.isdigit() or e == '.')
'1000.00'

Remove the $, any other character, except a digit or a . in one go.

查看更多
老娘就宠你
3楼-- · 2020-02-10 04:43

You could use replace to remove all commas:

"10,000.00".replace(",", "")

查看更多
Anthone
4楼-- · 2020-02-10 04:45

Update StephenPaulger's answer is better.

Original Answer

If you don't mind regular expressions you can also replace both $ and , in one go. Something like this:

>>> import re
>>> RawPurchaseAmount
'$10,000'
>>> re.sub('[\$,]', '', RawPurchaseAmount)
'10000'
>>> 

Remember to compile the regular expression if you plan to do this many times in the same program.

查看更多
▲ chillily
5楼-- · 2020-02-10 04:46
>>> import re
>>> re.sub("[^\d\.]", "", "$1,000,000.01")
'1000000.01'

Regular expression pattern says "anything that isn't a number or a decimal point". Anything matching that regex is replaced with "".

You may need to bear in mind that some European countries use . as the thousand seperator and , as the decimal mark.

So "one million euros and 5 cents" could be €1.000.000,05 or €1,000,000.05

查看更多
登录 后发表回答