Python: Converting string into decimal number

Sankar A picture Sankar A · Jan 10, 2011 · Viewed 157.9k times · Source

I have a python list with strings in this format:

A1 = [' "29.0" ',' "65.2" ',' "75.2" ']

How do I convert those strings into decimal numbers to perform arithmetic operations on the list elements?

Answer

Mark Byers picture Mark Byers · Jan 10, 2011

If you want the result as the nearest binary floating point number use float:

result = [float(x.strip(' "')) for x in A1]

If you want the result stored exactly use Decimal instead of float:

from decimal import Decimal
result = [Decimal(x.strip(' "')) for x in A1]