插件窝 干货文章 Python 中如何实现字符串的精准对齐与填充

Python 中如何实现字符串的精准对齐与填充

对齐 text Python aligned 716    来源:    2025-03-13

在 Python 中,可以使用字符串的 ljust()rjust()center() 方法来实现字符串的精准对齐与填充。这些方法允许你指定字符串的总宽度以及填充字符(默认为空格)。

1. ljust() 方法

ljust(width[, fillchar]) 方法用于将字符串左对齐,并使用指定的填充字符(默认为空格)填充到指定宽度。

text = "Python"
aligned_text = text.ljust(10, '-')
print(aligned_text)  # 输出: "Python----"

2. rjust() 方法

rjust(width[, fillchar]) 方法用于将字符串右对齐,并使用指定的填充字符(默认为空格)填充到指定宽度。

text = "Python"
aligned_text = text.rjust(10, '-')
print(aligned_text)  # 输出: "----Python"

3. center() 方法

center(width[, fillchar]) 方法用于将字符串居中对齐,并使用指定的填充字符(默认为空格)填充到指定宽度。

text = "Python"
aligned_text = text.center(10, '-')
print(aligned_text)  # 输出: "--Python--"

4. 使用 format() 方法

你也可以使用 format() 方法来实现字符串的对齐与填充。format() 方法提供了更灵活的格式化选项。

  • 左对齐:{:<width}
  • 右对齐:{:>width}
  • 居中对齐:{:^width}
text = "Python"
# 左对齐
aligned_text = "{:<10}".format(text)
print(aligned_text)  # 输出: "Python    "

# 右对齐
aligned_text = "{:>10}".format(text)
print(aligned_text)  # 输出: "    Python"

# 居中对齐
aligned_text = "{:^10}".format(text)
print(aligned_text)  # 输出: "  Python  "

5. 使用 f-string(Python 3.6+)

在 Python 3.6 及以上版本中,可以使用 f-string 来实现字符串的对齐与填充。

text = "Python"
# 左对齐
aligned_text = f"{text:<10}"
print(aligned_text)  # 输出: "Python    "

# 右对齐
aligned_text = f"{text:>10}"
print(aligned_text)  # 输出: "    Python"

# 居中对齐
aligned_text = f"{text:^10}"
print(aligned_text)  # 输出: "  Python  "

6. 指定填充字符

format() 和 f-string 中,你可以在对齐符号前指定填充字符。

text = "Python"
# 左对齐,填充 '-'
aligned_text = f"{text:-<10}"
print(aligned_text)  # 输出: "Python----"

# 右对齐,填充 '-'
aligned_text = f"{text:->10}"
print(aligned_text)  # 输出: "----Python"

# 居中对齐,填充 '-'
aligned_text = f"{text:-^10}"
print(aligned_text)  # 输出: "--Python--"

总结

  • ljust()rjust()center() 是字符串对象的内置方法,用于简单的对齐与填充。
  • format() 和 f-string 提供了更灵活的格式化选项,适合复杂的字符串格式化需求。

根据你的具体需求,可以选择合适的方法来实现字符串的精准对齐与填充。