Search code examples
pythonpython-docx

How to change the font of particular text in a paragraph when writing a word document using Python-docx?


I am using Python to parse an excel spreadsheet and write documentation to a word document. I want to highlight binary substrings e.g. '001' by having the numbers appear in dark red. I can find the substrings using re being any text which is a binary number sequence between single quotes, that is not my question. The question is how do I put the highlighting on just those characters within the paragraph? The format I would like to end up with is like the following:

final format

Any help would be appreciated.


Solution

  • from docx import Document 
    from docx.shared import RGBColor 
    
    document = Document() 
    run = document.add_paragraph()
    binary_run = run.add_run('your_binary_code')
    binary_run.font.color.rgb =  RGBColor(rgb_color_code_goes_here)
    cmplt_run = binary_run.add_run('rest of the text goes here')
    

    This will change the font color of ur binary code to the color code you provide. Refer python-docx documemtation to understand more.