当我运行以下
prices = [price.text.strip() for price in soup.select('.special-price')]
prices = prices.replace(u'\xa0', u' ')
print(prices)
我得到'list'对象没有属性'replace'
我应该把替换放在哪里?有什么方法可以一步清除它吗?
谢谢
因为'list' object has no attribute 'replace'
。这就是为什么。
你试图单独改变价格。字符串有replace
方法,但列表没有。
您应该为列表理解添加替换。
prices = [price.text.strip().replace(u'\xa0', u' ') for price in soup.select('.special-price')]
print(prices)
是的,因为您创建了一个包含列表推导的列表
您需要通过prices=''.join(prices)
将列表转换为字符串,假设价格是字符串列表,如果不将其解析为字符串。价格将是一个字符串。现在你可以调用替换它。
由于我们无法访问您的示例数据,因此应执行以下操作:
你需要把replace()
放在str
而不是list
,喜欢:
prices = ['1','1','2','3','4','5','1','1','1']
print([x.replace('1', '9') for x in prices])
OUTPUT:
['9', '9', '2', '3', '4', '5', '9', '9', '9']