AttributeError: the list object does not have a replace attribute when trying to delete a character

I am trying to remove a 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 an AttributeError error: the list object does not have a replace attribute

Based on php background, I'm not sure what is the right way to do this?

+8
source share
4 answers

xpath the method returns a list, you need to iterate over the elements.

kickoff = [item.replace("'", "") for item in kickoff]
+10
source
kickoff = tree.xpath('//*[@id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/b[1]/text()')

This code returns a list of non-string.Replace function will not work in the list.

[i.replace("'", "") for i in kickoff ]
+2
source

:

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("'", "")

, xpath . . , str, , . , !

0
source

This worked for me:

Image with working code. This error is caused by xpath being returned to the list. Lists do not have a replacement attribute. Thus, placing str in front of it, you convert it to a string that the code can handle. I hope this helps!

0
source

All Articles