Just replace the first node with the desired text:
tag.contents[0].replaceWith("new string")
Add in checks for an empty tag.contents if necessary.
-Aaron DeVore
On Tue, Jul 10, 2012 at 5:24 PM, bs4user <
sreht...@gmail.com> wrote:
> If a tag contains children, how can I change the text of the tag without
> changing or destroying the children?
>
> e.g., in a case like:
>
> <tag1> foo <tag2> abcdef <tag3> ghijkl </tag3></tag2></tag1>
>
> how can I change "foo" to "bar" without changing anything else?
>
> I cannot simply do:
> tag1.string = "bar"
> because, according to the BS4 documentation "Be careful: if the tag
> contained other tags, they and all their contents will be destroyed."