Search code examples
pythonpython-3.xpython-docx

How to ask python docx to write in italic type just


How to ask python docx to write in italic type but not the entire sentence, just some words ?

I have this code :

names = ["names1"]
dates = ["dates1"]
client = ["client1"]

from docx import Document

document = Document('filename.docx')

paragraphs = document.paragraphs




paragraphs[0].insert_paragraph_before("       To    "+names+"         Date  "+dates)
paragraphs[0].insert_paragraph_before("                                             ")
paragraphs[0].insert_paragraph_before("      From   "+names+"             Ref   "+client)
paragraphs[0].insert_paragraph_before("                                                ")

I know how to specify an entire sentence to be in italic type, but not how to tell python to transform just one word in italic type.

Here, I would like to transform To, Date, From, Ref but just those four word, not the rest.

Have you an idea how to do that ?


Solution

  • You can do something like this:

    p = document.add_paragraph()
    p.add_run('To').italic = True
    p.add_run(" "+names+" ")
    p.add_run('Date').italic = True
    

    and so on.