How do I parse a string to a float or int?

后端 未结 29 2801
醉话见心
醉话见心 2020-11-21 04:43

In Python, how can I parse a numeric string like \"545.2222\" to its corresponding float value, 545.2222? Or parse the string \"31\" t

29条回答
  •  孤独总比滥情好
    2020-11-21 05:01

    Localization and commas

    You should consider the possibility of commas in the string representation of a number, for cases like float("545,545.2222") which throws an exception. Instead, use methods in locale to convert the strings to numbers and interpret commas correctly. The locale.atof method converts to a float in one step once the locale has been set for the desired number convention.

    Example 1 -- United States number conventions

    In the United States and the UK, commas can be used as a thousands separator. In this example with American locale, the comma is handled properly as a separator:

    >>> import locale
    >>> a = u'545,545.2222'
    >>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    'en_US.UTF-8'
    >>> locale.atof(a)
    545545.2222
    >>> int(locale.atof(a))
    545545
    >>>
    

    Example 2 -- European number conventions

    In the majority of countries of the world, commas are used for decimal marks instead of periods. In this example with French locale, the comma is correctly handled as a decimal mark:

    >>> import locale
    >>> b = u'545,2222'
    >>> locale.setlocale(locale.LC_ALL, 'fr_FR')
    'fr_FR'
    >>> locale.atof(b)
    545.2222
    

    The method locale.atoi is also available, but the argument should be an integer.

提交回复
热议问题