簡體   English   中英

無法從 Python 3 中的字符串中刪除第一個字符

[英]Unable to remove first character from a string in Python 3

我正在使用 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)) 

上面的代碼沒有刪除第一個字符,output 是:

¥249.00
<類'海峽'>

但是,如果我切換到使用局部變量並嘗試刪除第一個字符,它工作正常

# 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))   

上面的代碼output是:

249.00
<類'海峽'>

我嘗試使用如下切片: currPrice = productPrice[1:]但仍然無法刪除第一個字符。 這可能是什么問題?

以防萬一模式仍然相同並且您只想獲得類似float的值,您可以通過貨幣符號split()strip()最后一個元素ResultSet

productPrice='\n¥249.00 '
currPrice = productPrice.split('¥')[-1].strip()

#output
#249.00

注意: Output 在將其轉換為真正的float之前仍然是一個string -> currPrice = float(currPrice)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM