python - 运行 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')
解决方案
传递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
推荐阅读
- android - 菜单中的 onOptionsItemSelected 对于使用 actionLayout 的项目是不可点击的
- java - 在线程 java.lang.RuntimeException 中获取异常:在同一阶段更改场景时 java.lang.reflect.InvocationTargetException
- java - 如何计算数组列表中的元素重复?
- c# - 有没有办法从导航页面更改主机窗口的大小和样式?(WPF)
- sql - Teradata SQL 周数 - 从 1 月 1 日开始的第 1 周,周数与一周中的特定日期对齐
- java - 无法通过 docker java 运行时从 ibm 云函数操作获取结果 json
- python - 带有--help arg的git子命令,不起作用
- math - 当光线沿法线行进时,Möller–Trumbore 距离不同于点平面距离
- activemq - ActiveMQ 日志代理插件
- sql-server - 如何带回未找到结果集的行