【问题标题】:Python parse comma-separated number into int [duplicate]Python将逗号分隔的数字解析为int [重复]
【发布时间】:2011-02-26 13:55:12
【问题描述】:

可能重复:
How do I use Python to convert a string to a number if it has commas in it as thousands separators?

如何在 Python 中将字符串 1,000,000(一百万)解析为整数值?

【问题讨论】:

标签: python string-conversion


【解决方案1】:
>>> a = '1,000,000'
>>> int(a.replace(',', ''))
1000000
>>> 

【讨论】:

    【解决方案2】:

    将 ',' 替换为 '',然后将整个内容转换为整数。

    >>> int('1,000,000'.replace(',',''))
    1000000
    

    【讨论】:

      【解决方案3】:

      还有一种简单的方法可以处理国际化问题:

      >>> import locale
      >>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
      'en_US.UTF-8'
      >>> locale.atoi("1,000,000")
      1000000
      >>> 
      

      我发现我必须像上面一样首先明确设置语言环境,否则它对我不起作用,我最终会得到一个丑陋的回溯:

      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "/usr/lib/python2.6/locale.py", line 296, in atoi
          return atof(str, int)
        File "/usr/lib/python2.6/locale.py", line 292, in atof
          return func(string)
      ValueError: invalid literal for int() with base 10: '1,000,000'
      

      【讨论】:

      • 你的意思是:locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') 即“UTF-8”,而不是“UTF8”。在我的 OSX 机器上,这似乎是正确的值。
      • 这应该是公认的答案。逗号替换 hack 很脆弱并且会破坏 i18n。
      • 这仍然会将错误的值(如 1,0,0,10)转换为 10010
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 2019-12-24
      • 2021-04-02
      • 2015-02-01
      • 1970-01-01
      相关资源
      最近更新 更多