无法从 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))
以上代码没有去掉第一个字符,输出为:
¥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
<class 'str'>
我尝试使用像这样的切片:currPrice = productPrice[1:]
但仍然无法删除第一个字符。这可能是什么问题?
以防万一模式仍然相同并且您只想获得 float
这样的值,您可以 split()
通过货币符号和 strip()
[=] 中的最后一个元素14=]:
productPrice='\n¥249.00 '
currPrice = productPrice.split('¥')[-1].strip()
#output
#249.00
注意: 输出仍然是 string
,直到您将其转换为真实的 float
-> currPrice = float(currPrice)
我正在使用 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
<class 'str'>
我尝试使用像这样的切片:currPrice = productPrice[1:]
但仍然无法删除第一个字符。这可能是什么问题?
以防万一模式仍然相同并且您只想获得 float
这样的值,您可以 split()
通过货币符号和 strip()
[=] 中的最后一个元素14=]:
productPrice='\n¥249.00 '
currPrice = productPrice.split('¥')[-1].strip()
#output
#249.00
注意: 输出仍然是 string
,直到您将其转换为真实的 float
-> currPrice = float(currPrice)