简体   繁体   English

无法从 Python 3 中的字符串中删除第一个字符

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

I'm using Beautiful Soup to crawl the data from a website.我正在使用 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)) 

The above code is not removing the first character, the output is:上面的代码没有删除第一个字符,output 是:

¥249.00 ¥249.00
<class 'str'> <类'海峡'>

However, if I switch to use local variable and try to remove the first character, it works fine但是,如果我切换到使用局部变量并尝试删除第一个字符,它工作正常

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

The above code output is:上面的代码output是:

249.00 249.00
<class 'str'> <类'海峡'>

I tried using slicing like: currPrice = productPrice[1:] but was still not able to remove the first character.我尝试使用如下切片: currPrice = productPrice[1:]但仍然无法删除第一个字符。 What can be the issue here?这可能是什么问题?

Just in case the pattern is still the same and you only like to get the float like value you can split() by currency sign and strip() the last element in ResultSet :以防万一模式仍然相同并且您只想获得类似float的值,您可以通过货币符号split()strip()最后一个元素ResultSet

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

#output
#249.00

Note: Output is still a string until you converted it to a real float -> currPrice = float(currPrice)注意: Output 在将其转换为真正的float之前仍然是一个string -> currPrice = float(currPrice)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM