将python字符串转换为整数,不带逗号

时间:2016-06-03 07:52:08

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

我使用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中字符串的值整数

4 个答案:

答案 0 :(得分:3)

你可以这样做:

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

答案 1 :(得分:1)

结帐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'>
>>> 

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

import re

''.join(re.findall(r'\d+', '82,000,00'))

或其他方法,

int(filter(str.isdigit, '82,000,00'))
相关问题