convert decimal mark

Till B picture Till B · Aug 18, 2011 · Viewed 75.2k times · Source

I have a CSV file with data reading that I want to read into Python. I get lists that contain strings like "2,5". Now doing float("2,5") does not work, because it has the wrong decimal mark.

How do I read this into Python as 2.5?

Answer

Lauritz V. Thaulow picture Lauritz V. Thaulow · Aug 18, 2011

You may do it the locale-aware way:

import locale

# Set to users preferred locale:
locale.setlocale(locale.LC_ALL, '')
# Or a specific locale:
locale.setlocale(locale.LC_NUMERIC, "en_DK.UTF-8")

print locale.atof("3,14")

Read this section before using this method.