Search code examples
pythonunicodedocxsubscriptsuperscript

How to add text in superscript or subscript with python docx


In the python docx quickstart guide (https://python-docx.readthedocs.io/en/latest/) you can see that it is possible to use the add_run-command and add bold text to a sentence.

document = Document()
document.add_heading('Document Title', 0)
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True

I would to use the same add_run-command but instead add text that is superscripted or subscripted.

Is this possible to achieve?

Any help much appreciated!

/V


Solution

  • The call to add_run() returns a Run object that you can use to change font options.

    from docx import Document
    document = Document()
    
    p = document.add_paragraph('Normal text with ')
    
    super_text = p.add_run('superscript text')
    super_text.font.superscript = True
    
    p.add_run(' and ')
    
    sub_text = p.add_run('subscript text')
    sub_text.font.subscript = True
    
    document.save('test.docx')
    

    enter image description here