[Tutor] ValueError: could not convert string to float: '13,2'

Mark Lawrence breamoreboy at yahoo.co.uk
Tue Dec 31 21:56:58 CET 2013


On 31/12/2013 13:53, Pierre Dagenais wrote:
> Hi,
>
> I'm trying to convert a list of strings to float. Unfortunately the
> numbers are written with a decimal comma instead of a decimal point.
> What is the best way to replace these commas with decimal points? Do I
> need to write a function that will iterate over every alphanumeric,
> replace the comma with a point and then rewrite the list, or is there a
> better way?
>
> Thank you,
>
> PierreD.

Change your locale.

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"))

See 
http://docs.python.org/3/library/locale.html#background-details-hints-tips-and-caveats 
for the background.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list