How to convert a string to a number if it has commas in it as thousands separators?

前端 未结 8 944
时光说笑
时光说笑 2020-11-22 08:10

I have a string that represents a number which uses commas to separate thousands. How can I convert this to a number in python?

>>> int(\"1,000,000         


        
相关标签:
8条回答
  • 2020-11-22 08:42

    I got locale error from accepted answer, but the following change works here in Finland (Windows XP):

    import locale
    locale.setlocale( locale.LC_ALL, 'english_USA' )
    print locale.atoi('1,000,000')
    # 1000000
    print locale.atof('1,000,000.53')
    # 1000000.53
    
    0 讨论(0)
  • 2020-11-22 08:42
    >>> import locale
    >>> locale.setlocale(locale.LC_ALL, "")
    'en_US.UTF-8'
    >>> print locale.atoi('1,000,000')
    1000000
    >>> print locale.atof('1,000,000.53')
    1000000.53
    

    this is done on Linux in US.

    0 讨论(0)
  • 2020-11-22 08:43

    I tried this. It goes a bit beyond the question: You get an input. It will be converted to string first (if it is a list, for example from Beautiful soup); then to int, then to float.

    It goes as far as it can get. In worst case, it returns everything unconverted as string.

    def to_normal(soupCell):
    ''' converts a html cell from beautiful soup to text, then to int, then to float: as far as it gets.
    US thousands separators are taken into account.
    needs import locale'''
    
    locale.setlocale( locale.LC_ALL, 'english_USA' ) 
    
    output = unicode(soupCell.findAll(text=True)[0].string)
    try: 
        return locale.atoi(output)
    except ValueError: 
        try: return locale.atof(output)
        except ValueError:
            return output
    
    0 讨论(0)
  • 2020-11-22 08:49

    Replace the commas with empty strings, and turn the resulting string into an int or a float.

    >>> a = '1,000,000'
    >>> int(a.replace(',' , ''))
    1000000
    >>> float(a.replace(',' , ''))
    1000000.0
    
    0 讨论(0)
  • 2020-11-22 08:50

    This works:

    (A dirty but quick way)

    >>> a='-1,234,567,89.0123'
    >>> "".join(a.split(","))
    '-123456789.0123'
    
    0 讨论(0)
  • 2020-11-22 08:55
    import locale
    locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) 
    locale.atoi('1,000,000')
    # 1000000
    locale.atof('1,000,000.53')
    # 1000000.53
    
    0 讨论(0)
提交回复
热议问题