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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:09:40  来源:igfitidea点击:

AttributeError: 'list' object has no attribute 'replace' when trying to remove character

pythonxmlstringlistxpath

提问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

xpathmethod returns a list, you need to iterate items.

xpath方法返回一个列表,您需要迭代项目。

kickoff = [item.replace("'", "") for item in kickoff]

回答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 放在它之前,您可以将其转换为代码可以处理的字符串。我希望这有帮助!