[英]AttributeError: 'list' object has no attribute 'replace' when trying to remove character
I am trying to remove the character ' from my string by doing the following 我试图通过执行以下操作从我的字符串中删除字符'
kickoff = tree.xpath('//*[@id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/b[1]/text()')
kickoff = kickoff.replace("'", "")
This gives me the error AttributeError: 'list' object has no attribute 'replace' 这给了我错误AttributeError:'list'对象没有属性'replace'
Coming from a php background I am unsure what the correct way to do this is? 来自php背景我不确定这样做的正确方法是什么?
xpath
方法返回一个列表,需要迭代项。
kickoff = [item.replace("'", "") for item in kickoff]
kickoff = tree.xpath('//*[@id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/b[1]/text()')
此代码返回列表而不是string.Replace函数将无法在列表上工作。
[i.replace("'", "") for i in kickoff ]
This worked for me: 这对我有用:
kickoff = str(tree.xpath('//*[@id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/b[1]/text()'))
kickoff = kickoff.replace("'", "")
This error is caused because the xpath returns in a list. 导致此错误的原因是xpath在列表中返回。 Lists don't have the replace attribute.
列表没有replace属性。 So by putting str before it, you convert it to a string which the code can handle.
因此,通过在它之前放置str,可以将其转换为代码可以处理的字符串。 I hope this helped!
我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.