在Python中,您可以使用字符串的`ljust()`, `rjust()`, 和 `center()` 方法来实现左对齐、右对齐和居中对齐。以下是这些方法的使用示例:
左对齐(`ljust`)
text = "Hello"left_aligned = text.ljust(20) 左对齐,右侧填充空格print(left_aligned) 输出:Hello(右侧填充空格)
右对齐(`rjust`)
text = "Hello"right_aligned = text.rjust(20) 右对齐,左侧填充空格print(right_aligned) 输出:Hello(左侧填充空格)
居中对齐(`center`)
text = "Hello"centered = text.center(20) 居中对齐,两侧填充空格print(centered) 输出:Hello(两侧填充空格)

使用`format`函数格式化
text = "Hello"left_aligned = "{:<10}".format(text) 左对齐,宽度为10,左侧填充空格right_aligned = "{:>10}".format(text) 右对齐,宽度为10,右侧填充空格centered = "{:^10}".format(text) 居中对齐,宽度为10,两侧填充空格print(left_aligned) 输出:Hello(左侧填充空格)print(right_aligned) 输出:Hello(右侧填充空格)print(centered) 输出:Hello(两侧填充空格)
使用`python-docx`库设置段落对齐方式
from docx import Documentfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENTdoc = Document()p = doc.add_paragraph('这是一段左对齐的文本。')p.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT 左对齐p2 = doc.add_paragraph('这是一段右对齐的文本。')p2.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT 右对齐doc.save('aligned_text.docx')
