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

104,450

Solution 1

xpath method returns a list, you need to iterate items.

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

Solution 2

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 ]

Solution 3

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!

Share:
104,450
emma perkins
Author by

emma perkins

Updated on July 19, 2020

Comments

  • emma perkins
    emma perkins almost 4 years

    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'

    Coming from a php background I am unsure what the correct way to do this is?

  • emma perkins
    emma perkins about 8 years
    Thanks - this is whats confused me ... little bit different to php in the sense :)
  • falsetru
    falsetru about 8 years
    @emmaperkins, list's methods are different from str's methods.