January 15th, 2008, 08:46 PM
Convert string to float?
Hello, I have a simple question.
I have a string like '$29.99' and I would like to convert it to a float so that's only 29.99. I would prefer doing this without having to manually remove the $ since it may not be a $ all the time. Is there a parsing function for doing this? Thanks.
January 16th, 2008, 04:21 AM
I'm not sure what you are exactly thinking, but following function should help you somehow.
if len(moneyString) > 0:
if moneyString in ['$', '£']:
raise Exception('Empty string')
January 16th, 2008, 09:49 AM
It throws the exception you need:
- ValueError: empty string for float()
- ValueError: invalid literal for float(): xxxxx
January 17th, 2008, 04:14 PM
float_pat = re.compile('[0-9]+(\.[0-9]+)?')
if re.search(float_pat, s) is not None:
# Do something
This would grab the first substring that resembles a float from the string “s” and do something with it.