print 函数打印格式化

在 Python 中,print 函数本身不能直接实现指定长度打印、以指定字符填充以及左对齐右对齐等功能,但可以通过字符串格式化的方法来达到这些目的,然后使用 print 函数输出格式化后的字符串。下面为你详细介绍几种常用的实现方式:

1. 使用 str.format() 方法

str.format() 是 Python 中常用的字符串格式化方法,可以方便地实现指定长度、填充字符以及对齐方式。

示例代码

text = "Hello"
# 左对齐,长度为 10,用 * 填充
left_aligned = "{:*<10}".format(text)
print(left_aligned)

# 右对齐,长度为 10,用 * 填充
right_aligned = "{:*>10}".format(text)
print(right_aligned)

# 居中对齐,长度为 10,用 * 填充
center_aligned = "{:*^10}".format(text)
print(center_aligned)

代码解释

  • {:*<10}:表示左对齐,总长度为 10,不足的部分用 * 填充。
  • {:*>10}:表示右对齐,总长度为 10,不足的部分用 * 填充。
  • {:*^10}:表示居中对齐,总长度为 10,不足的部分用 * 填充。

2. 使用 f-string(Python 3.6 及以上版本支持)

f-string 是 Python 3.6 引入的一种更简洁的字符串格式化方式,同样可以实现上述功能。

示例代码

text = "Hello"
# 左对齐,长度为 10,用 * 填充
left_aligned = f"{text:*<10}"
print(left_aligned)

# 右对齐,长度为 10,用 * 填充
right_aligned = f"{text:*>10}"
print(right_aligned)

# 居中对齐,长度为 10,用 * 填充
center_aligned = f"{text:*^10}"
print(center_aligned)

代码解释

f-string 的语法更加简洁,直接在字符串前加上 f,然后在大括号内使用格式化表达式。其格式化规则与 str.format() 方法类似。

3. 使用 ljust()rjust()center() 方法

Python 字符串对象本身提供了 ljust()rjust()center() 方法,也可以实现左对齐、右对齐和居中对齐,并以指定字符填充。

示例代码

text = "Hello"
# 左对齐,长度为 10,用 * 填充
left_aligned = text.ljust(10, '*')
print(left_aligned)

# 右对齐,长度为 10,用 * 填充
right_aligned = text.rjust(10, '*')
print(right_aligned)

# 居中对齐,长度为 10,用 * 填充
center_aligned = text.center(10, '*')
print(center_aligned)

代码解释

  • ljust(width, fillchar):返回一个左对齐的字符串,总长度为 width,不足的部分用 fillchar 填充。
  • rjust(width, fillchar):返回一个右对齐的字符串,总长度为 width,不足的部分用 fillchar 填充。
  • center(width, fillchar):返回一个居中对齐的字符串,总长度为 width,不足的部分用 fillchar 填充。
使用 Hugo 构建
主题 StackJimmy 设计