我正在使用 Beautiful Soup 從網站上抓取資料。
# Get the price
# productPrice = "¥249.00"
productPrice = soup.find('span', class_='price').text # this line returns a string ¥249.00
currPrice = productPrice.lstrip("¥") # remove currency sign
print(currPrice)
print(type(currPrice))
上面的代碼沒有洗掉第一個字符,輸出是:
¥249.00
<class 'str'>
但是,如果我切換到使用區域變數并嘗試洗掉第一個字符,它作業正常
# Get the price
productPrice = "¥249.00"
# productPrice = soup.find('span', class_='price').text # this line returns a string ¥249.00
currPrice = productPrice.lstrip("¥") # remove currency sign
print(currPrice)
print(type(currPrice))
上面的代碼輸出是:
249.00
<類'str'>
我嘗試使用如下切片:currPrice = productPrice[1:]但仍然無法洗掉第一個字符。這里可能是什么問題?
uj5u.com熱心網友回復:
以防萬一模式仍然相同,并且您只想通過貨幣符號和最后一個元素獲得float類似的值:split()strip()ResultSet
productPrice='\n¥249.00 '
currPrice = productPrice.split('¥')[-1].strip()
#output
#249.00
注意: 輸出仍然是 astring直到您將其轉換為真實float->currPrice = float(currPrice)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/443807.html
下一篇:如何匹配字串的通配符?
