Python AttributeError: 'list' 对象在尝试删除字符时没有属性 'replace'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36642782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AttributeError: 'list' object has no attribute 'replace' when trying to remove character
提问by emma perkins
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' object has no attribute 'replace'
Coming from a php background I am unsure what the correct way to do this is?
来自 php 背景,我不确定这样做的正确方法是什么?
回答by falsetru
回答by Himanshu dua
kickoff = tree.xpath('//*[@id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/b[1]/text()')
This code is returning list not a string.Replace function will not work on list.
此代码返回列表而不是字符串。替换函数不适用于列表。
[i.replace("'", "") for i in kickoff ]
回答by Char Gamer
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. Lists don't have the replace attribute. So by putting str before it, you convert it to a string which the code can handle. I hope this helped!
导致此错误的原因是 xpath 在列表中返回。列表没有替换属性。因此,通过将 str 放在它之前,您可以将其转换为代码可以处理的字符串。我希望这有帮助!