Python 字符串到float和regex
我的正则表达式和字符串有问题 我需要一个解决方案,在我的正则表达式代码采取浮点数的字符串。我不知道为什么这个代码不起作用Python 字符串到float和regex,python,regex,string,floating-point,Python,Regex,String,Floating Point,我的正则表达式和字符串有问题 我需要一个解决方案,在我的正则表达式代码采取浮点数的字符串。我不知道为什么这个代码不起作用 from bs4 import BeautifulSoup import urllib2 from re import sub url = 'http://www.ebay.es/itm/PET-SHOP-BOYS-OFFICIAL-PROMO-BARCELONA-ELECTRIC-TOUR-BEER-CERVEZA-20cl-BOTTLE-/111116266655'
from bs4 import BeautifulSoup
import urllib2
from re import sub
url = 'http://www.ebay.es/itm/PET-SHOP-BOYS-OFFICIAL-PROMO-BARCELONA-ELECTRIC-TOUR-BEER-CERVEZA-20cl-BOTTLE-/111116266655' #raw_input('Dime la url que deseas: ')
code = urllib2.urlopen(url).read();
soup = BeautifulSoup(code)
info = soup.find('span', id='v4-27').contents[0]
print info
info = sub("[\D]+,+[\D]", "", info)
i = float(info)
print i
\D
表示非数字。您需要改用\d
。详情请看这里:
已更新
我明白了,您的方法是替换所有非数字字符。在我看来,匹配所需的信息更加清晰:
>>> import re
>>> s = "15,00 EUR"
>>> price_string = re.search('(\d+,\d+)', s).group(1)
>>> price_string
'15,00'
>>> float(price_string.replace(',', '.'))
15.0