0

I want to replace a word in my paragraph with a hyperlink. I saw functions that can create a new word with hyperlink but that's not what I want. For example I want to do something like this:

mydoc = docx.Document()
text = "a stackoverflow question"
parag = mydoc.add_paragraph(text)
parag.add_hyperlink(the word that will be changed to the hyperlink (in that case
                    that can be "stackoverflow"), link('https://stackoverflow.com'))

With this add_hyperlink function, the stackoverflow word must be a hyperlink. Is there any way to do this?

Nurqm
  • 4,715
  • 2
  • 11
  • 35
  • You can follow the solution proposed by @scanny [here](https://stackoverflow.com/questions/24805671/how-to-use-python-docx-to-replace-text-in-a-word-document-and-save)! – Tone Aug 22 '20 at 10:45
  • It didn't work, it needs string but mine is hyperlink so I got this error `TypeError: 'in ' requires string as left operand, not CT_R` – Nurqm Aug 22 '20 at 10:53

1 Answers1

0

Build up the paragraph run by run, something like:

document = docx.Document()
paragraph = mydoc.add_paragraph()
paragraph.add_run("a ")
paragraph.add_hyperlink("stackoverflow", link('https://stackoverflow.com'))
paragraph.add_run("question")

A hyperlink must appear as its own run, so you need a separate run before and after if you want to put it in the middle of a sentence.

scanny
  • 26,423
  • 5
  • 54
  • 80
  • This worked but kinda different. After I add this, when I run my script, it starts overwriting to the old file everytime I restart the program. Then I deleted these lines but problem is still continue. I'm confused, I litterally change nothing except the code that you write. – Nurqm Aug 23 '20 at 20:45
  • Even in that code, it's overwriting the old file. This wasn't happening before I don't know what happend. Do you have any idea? `import docx` `myfile = docx.Document()` `parag = myfile.add_paragraph('test')` `myfile.save('myfile.docx')` – Nurqm Aug 23 '20 at 21:29