In my assignment when I ask for user input I need to get a number, but the user can enter a dollar sign, comma, and period and that shouldn't bother my program.
In the past I've done this by taking what ever input the user gives, then "correcting the data" by using conditionals like
>>> if x == $
I would take off the dollar sign, etc.
I would imagine there's a more efficient way to do this? Any ideas?
Thanks in advance.
- husoskiLv 71 month ago
The shortest code I can think of to remove unwanted characters is something like:
original = '$1,234.56'
filtered = ''.join(c for c in original if c not in '$,')
print(original, '-->', filtered)
That doesn't guarantee that what remains in the filtered string is a valid number, though. Brilliant_moves gives a very good example of dealing with that, along a nice, easier-to-read method of doing the filtering.
Both methods will turn garbage into valid numbers. Feed in '1,$2,3$4' as an original string and both ideas will convert that into the number 1234.
To explain how my example works, start with the .join() method of a string. The s.join() method concatenates a bunch of separate strings into a single result, with the string s inserted as a separator.
The "c for c in original" in the argument is the start of a "generator expression" that generates a series of single characters from the string "original"; and the "if c not in '$,'" condition says to only include characters that are not '$' or ',' in the series.
This is very much like the loop:
result = 
for c in original:
if c not in '$,':
...except that a generator will produce the result characters as needed, without needing to store the whole series in a list object.
Try some of this out in IDLE or interactive mode. Maybe you'll get the itch to learn some Python that wasn't in your class or tutorial.
- brilliant_movesLv 71 month ago
Here's one way:
ans = ''
for c in s:
if c=='$' or c==',':
amount = removeSurplus ('$1,000.00')
dollars = float (amount)
print ("That's not an amount in dollars.")
print ("%.2f dollars" % dollars)