float("1,009.67") error

Chris Rebert clp2 at rebertia.com
Wed Jun 3 11:42:26 EDT 2009


On Wed, Jun 3, 2009 at 8:29 AM, Jianli Shen <wjxiaoshen at gmail.com> wrote:
> I want to converter a string 1,009.67 to float, I got:
> python ValueError: invalid literal for float()
> how do I handle this.
>
> 1,009.67 is generated by some other program. It could be 2,898.88
> 3,554,545.66 etc.

Python's literal float syntax does not allow the use of commas as a
thousands separator. Eliminate the commas before passing the string to
float(). This can be done by calling .replace(',','') on the string
and passing the result to float().
You would also be well advised to read the Python tutorial if you
haven't already.

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list