首页 > 解决方案 > 运行 center() 命令时文本不会居中

问题描述

我试图在表格中居中文本,我设法用 .strip() 从字符串的开头/结尾删除了空格,但是当我尝试运行它时 .center() 不起作用。有人可以告诉我为什么/如何解决它吗?附上代码和当前输出。

from docx import Document
from docx.shared import Inches
from docx.shared import Pt
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

doc = Document('test.docx')
new_doc = Document()
sections = new_doc.sections
for section in sections:
    section.left_margin = Inches(3)
    section.right_margin = Inches(3)
for para in doc.paragraphs:
    para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    table = new_doc.add_table(rows=1, cols=1)
#    table.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
    table.style = 'Table Grid'
    text = para.text.strip()
    # get = int(len(text))
    # run = text.center(int(get), ' ')
    # for para.text in text:
    #     get = int(len(text))
    cells = table.rows[0].cells
    cells[0].text = text
#    cells[0].vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
    paragraph = new_doc.add_paragraph('')
    paragraph.paragraph_format.space_after = Pt(0)
new_doc.save('details.docx')

输出:输出

标签: pythonstringtextms-wordpython-docx

解决方案


传递len(x)center使其成为空操作。

>>> 'hi'.center(len('hi'), ' ')
'hi'
>>> 'hi'.center(20, ' ')
'         hi         '

您可以按行拆分并以某个给定的宽度居中,但这并不理想,因为您必须自己选择宽度,甚至可能拆分行/进行自动换行(当文档已经具有此逻辑时)。

您可能希望在 word 本身中执行此操作:例如,搜索“python docx center text”会给出 https://python-docx.readthedocs.io/en/latest/api/enum/WdAlignParagraph.html

from docx.enum.text import WD_ALIGN_PARAGRAPH

paragraph = document.add_paragraph()
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

您可能会在代码中应用与

para.alignment = WD_ALIGN_PARAGRAPH.CENTER

推荐阅读