Getting and vetting a decimal number, like a dollar amount or an annual interest rate, ought to be a lot easier than it is. I keep thinking there has to be an easier way. I would love to have your input. I will save you the tortuous mental process I went through but here is what I finally decided. Given: you know your entry will be a string. Ok! First, even when you tell them not to, almost everybody entering a large sum of money will slip up and put a positional comma in their input. So don’t fuss at your user, just deal with it. It’s not that hard:
def zap_commas(num): if "," in num: # some users insist on using commas num = "".join(num.split(",")) # so remove them and continue checking return num
I decided on paring two string tools, .join and .split, to do the job. If there are commas in the user’s input, we are going to tear it apart and reassemble it without them.
I think .split(separator character) was probably developed with long string file objects in mind. For example, using a period as our separator, if we apply .split(“.”) to: test=”One. Two. Buckle my shoe.”, we will get a csv (comma separated values) list of sentences without the period separators, ie.:
[‘One’, ‘ Two’, ‘ Buckle my shoe’, ”] Note that the final period here generates a final null entry. The important thing is that it will work on any string and is perfectly happy to use commas as its split separator. So 1,234,567.89 tears into this list: [‘1’, ‘234’, ‘567.89’]. You can not, by the way, employ an empty separator.
“”.join() is one of the most misunderstood string tools in Python because it does not follow the string-dot-function-options general format. You begin by defining a separator. In this case our separator is null – an empty string – which is acceptable in this tool; .join takes this separator and then concatenates a series of strings (usually members of a list) with the defined separator between each. The pattern it yields is string-separator-string-separator, etcetera on ad infinitum. If the separator is null then we get a string-string-string pattern. What split has torn asunder, join will reassemble – but without the commas.
This does NOT mean we now have a usable number, just the the string we started with no long contains any commas.