【问题标题】:Convert python string into integer without commas in them [duplicate]将python字符串转换为没有逗号的整数[重复]
【发布时间】:2016-10-03 04:43:18
【问题描述】:

我正在使用 beautifulsoup4 从网站中提取价格标签。我使用的代码是这样的

 #price
        try:
            price = soup.find('span',{'id':'actualprice'})
            price_result= str(price.get_text())
            print "Price: ",price_result
        except StandardError as e:
            price_result="Error was {0}".format(e)
            print price_result

我得到的输出是一个带有逗号格式的字符串。例如 82,000,00

我想要什么:

将格式从字符串价格更改为不带逗号的整数价格,以便我可以将它们用作 excel 中字符串的值

【问题讨论】:

  • “没有逗号”是什么意思?您想从号码中删除逗号,还是简单地将其更改为点?
  • 我只想在提取时将其用作数字,以便进行计算。
  • 不带逗号的更清楚
  • 这是一个奇怪的符号。通常为 82,000.00 或 82.000,00。 “数字”总是这样的格式吗?

标签: python string python-2.7 python-3.x beautifulsoup


【解决方案1】:

你可以这样做:

>>> string = '82,000,00'
>>> int(price_result.replace(',', ''))
8200000

【讨论】:

  • 这不是让它变大 100 倍吗?
  • 取决于第二个逗号是否分隔小数部分。这个问题不清楚...
  • 没有意义。这解决了
  • 如果我使用上面的方法,我会得到这个invalid literal for int() with base 10: ''
【解决方案2】:

Checkout https://docs.python.org/2/library/string.htmlhttps://docs.python.org/3/library/string.html 取决于您使用的 Python 版本并使用“replace()”函数:

int_price = int(price_result.replace(',',''))

这会替换字符串中的所有逗号,然后将其转换为 INT:

>>> price = "1,000,000"
>>> type(price)
<type 'str'>
>>> int_price = int(price.replace(',',''))
>>> type(int_price)
<type 'int'>
>>> 

【讨论】:

    【解决方案3】:

    如果最后一部分是小数部分,你可以这样做:

    import re
    r = re.compile(r'((?:\d{1,3},?)+)(,\d{2})')
    m = r.match('82,000,00')
    v = m.group(1).replace(',', '') + m.group(2).replace(',', '.')
    print(float(v))
    

    输出:

    82000.0
    

    【讨论】:

      【解决方案4】:
      import re
      
      ''.join(re.findall(r'\d+', '82,000,00'))
      

      或者另一种方法,

      int(filter(str.isdigit, '82,000,00'))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多