在 Python 中,可以使用字符串的 ljust()
、rjust()
和 center()
方法来实现字符串的精准对齐与填充。这些方法允许你指定字符串的总宽度以及填充字符(默认为空格)。
ljust()
方法ljust(width[, fillchar])
方法用于将字符串左对齐,并使用指定的填充字符(默认为空格)填充到指定宽度。
text = "Python"
aligned_text = text.ljust(10, '-')
print(aligned_text) # 输出: "Python----"
rjust()
方法rjust(width[, fillchar])
方法用于将字符串右对齐,并使用指定的填充字符(默认为空格)填充到指定宽度。
text = "Python"
aligned_text = text.rjust(10, '-')
print(aligned_text) # 输出: "----Python"
center()
方法center(width[, fillchar])
方法用于将字符串居中对齐,并使用指定的填充字符(默认为空格)填充到指定宽度。
text = "Python"
aligned_text = text.center(10, '-')
print(aligned_text) # 输出: "--Python--"
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 "
在 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 "
在 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 提供了更灵活的格式化选项,适合复杂的字符串格式化需求。根据你的具体需求,可以选择合适的方法来实现字符串的精准对齐与填充。