如何实现python3中的字符串对齐?

Python3提供ljust()、rjust()、center()及format()、f-string实现字符串对齐,用于格式化输出;ljust(width, fillchar)左对齐右填充,rjust(width, fillchar)右对齐左填充,center(width, fillchar)居中两侧填充;format()用""、"^"控制左、右、居中对齐;f-string(推荐)语法更简洁高效,如f"{text:{fill}

Python3 提供了多种字符串对齐方式,主要通过内置的字符串方法实现,适用于格式化输出、表格展示等场景。核心方法包括 ljust()rjust()center(),也可以使用 format() 或 f-string 进行更灵活的控制。

使用 ljust()、rjust()、center() 方法

这三个方法用于将字符串左对齐、右对齐或居中对齐,并填充至指定宽度。

说明:
  • ljust(width, fillchar):左对齐,右侧填充
  • rjust(width, fillchar):右对齐,左侧填充
  • center(width, fillchar):居中对齐,两侧填充
示例:
text = "Hello"
print(text.ljust(10, '-'))   # 输出: Hello-----
print(text.rjust(10, '-'))   # 输出: -----Hello
print(text.center(10, '-'))  # 输出: --Hello---

使用 str.format() 实现对齐

在 format() 中可以使用格式控制符指定对齐方式。

常用对齐符号:
  • :左对齐
  • >:右对齐
  • ^:居中对齐
示例:
print("{:<10}".format("Hello"))  # 左对齐
print("{:>10}".format("Hello"))  # 右对齐
print("{:^10}".format("Hello"))  # 居中对齐

使用 f-string(推荐,Python 3.6+)

f-string 写法更简洁,适合现代 Python 开发。

示例:
text = "Hello"
width = 10
fill = '-'

print(f"{text:{fill}<{width}}") # 左对齐: Hello----- print(f"{text:{fill}>{width}}") # 右对齐: -----Hello print(f"{text:{fill}^{width}}") # 居中对齐: --Hello---

基本上就这些。根据使用习惯选择方法即可,f-string 更高效也更易读。对齐时注意宽度设置合理,避免截断或错位。不复杂但容易忽略细节。