Martin Massera
Martin Massera

Reputation: 1912

BeautifulSoup - replacing string not working

I have a node of type NavigableString and I want to replace the contents. According to documentation, it should be like this:

node.string = 'new string'

however, if I inspect it doesn't work:

print unicode(node)        ---> prints 'old string'
node.string = 'new string'
print unicode(node)        ---> should print 'new string' but prints 'old string'

any ideas?

Upvotes: 1

Views: 1332

Answers (1)

MD. Khairul Basar
MD. Khairul Basar

Reputation: 5110

You need to use replace_with() method to replace string.

From official documentation, it says

You can’t edit a string in place, but you can replace one string with another, using replace_with()

node.string.replace_with("new string")

You can check here.

EDIT

As you mentioned node is a NavigableString, you don't need to change its .string attribute. You should do -

node = "new string"

If node is a tag then you should change its .string attribute.

Upvotes: 4

Related Questions