3

How to parse floats in Python from a source which uses a special known local format that has commas as decimal separators?

locale can do that, of course. But its documentation says:

It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program. Saving and restoring it is almost as bad: it is expensive and affects other threads that happen to run before the settings have been restored.

Simply replacing , by . is not such a great solution either.

Can a special locale in Python be used but only for a single parse operation?

Amaterasu
  • 153
  • 10
  • 1
    I do not know good way. `locale` is in any case bad: it is done mostly for the inverse operation, so you may get "correct" unicode character and not the ASCII equivalent you may often get in inputs (hyphen and space/non-breaking space are the big offenders). ICU (from Unicode) has some better locale handling (mostly because localization is now better known as the early Unix time, and Unicode knows something about it). But also ICU do not solve the different needs in the two directions – Giacomo Catenazzi Dec 21 '21 at 14:26
  • @GiacomoCatenazzi ok, let's stick to `float(s.replace(",", "."))` then – Amaterasu Dec 22 '21 at 08:36
  • Yeah, usually I do so, but I have a simpler problem. I can set the locale, so I try with locale, and if I get an exception, I replace ',' with point (and remove spaces). – Giacomo Catenazzi Dec 22 '21 at 08:46

0 Answers0