Search code examples
pythonlogicpython-docx

How to add text to paragraphs similar to table cells


First time posting on SE so apologies for wonky formatting. I am a novice python and the python-docx module so I may be missing something basic in my code. Essentially, I am trying to include an "add_paragraph" inside a for loop so that every run through the loop it will add +1 value to the paragraph text.

I have been able to iterate through a table's cells similar to this:

document= document(filename.docx)

for x in range(0,3): ##creates 3 tables
     table = document.add_table(rows=3,cols=3)

for y in range(0,3):
     for z in range(0,3):
          tablecells = document.tables[x].rows[y].cells
          tablecells[0].text = 'Column 0, cell %d' % (z)

The out put of this code would give me something like this in the first column of the first table:

|------------------|--------------|---------|
|Column 0, cell 0  |              |         |
|------------------|--------------|---------|
|Column 0, cell 1  |              |         |
|------------------|--------------|---------|
|Column 0, cell 2  |              |         |
|------------------|--------------|---------|

So this method works great for populating a table with pre known values.

I would like to know if there's a way to do this with paragraphs instead of table cells. My pseudo code would be something like this:

for x in range(1,4):
     document.add_paragraph('This is paragraph %d') % (x)

My expected result is this:

This is paragraph 1

This is paragraph 2

This is paragraph 3

However, if try to run this code I get this error:

TypeError: unsupported operand type(s) for %: 'Paragraph' and 'int'

I hope I made this clear and thank you in advance for any help and knowledge!


Solution

  • Change this

    for x in range(1,4):
         document.add_paragraph('This is paragraph %d') % (x)
    

    to

    for x in range(1,4):
         document.add_paragraph('This is paragraph %d' % (x))
    

    The 1st piece of code tries to implement the % operator on the result of document.add_paragraph('This is paragraph %d') and x which should be the Paragraph (object) that is mentioned in the error.

    while the second piece is what you want , namely apply % operator on a string and replace the %d with the value of x.