Saturday 7 November 2020

Locale-aware string formatting using .format() syntax

Is there a (general) way to do locale-aware string formatting in Python using the .format() {:} syntax? I know of locale.format_string(), but this only accepts the old % syntax. {:n} exists, but only works as a replacement of {:d}, not for the other formats.

My current approach is below, which I expect will break for most non-trivial cases.

import locale
import string


class LocaleFormatter(string.Formatter):
    def format_field(self, value, format_spec):
        if format_spec[-1] not in 'eEfFgGdiouxXcrs':  # types copied from locale._percent_re
            return super().format_field(value, format_spec)
        grouping = ',' in format_spec or '_' in format_spec
        format_spec = '%' + format_spec.replace(',', '').replace('_', '')
        return locale.format_string(format_spec, value, grouping)


locale.setlocale(locale.LC_ALL, '')
fmt = LocaleFormatter()
fmt.format("Length: {:,.2f} mm, width: {:,.2f} mm", 1234.56, 7890)  # expected format is 1.234,56 for most locales


from Locale-aware string formatting using .format() syntax

No comments:

Post a Comment