温馨提示×

如何在Python中使用format()函数进行对齐操作

小樊
93
2024-08-23 10:49:26
栏目: 编程语言

在Python中使用format()函数进行对齐操作可以通过在花括号中添加冒号(:)和对齐格式进行控制。以下是一些示例:

  1. 居左对齐:
text = "hello"
print("{:<10}".format(text))
# 输出结果为:"hello     "
  1. 居中对齐:
text = "hello"
print("{:^10}".format(text))
# 输出结果为:"  hello   "
  1. 居右对齐:
text = "hello"
print("{:>10}".format(text))
# 输出结果为:"     hello"

在上面的示例中,数字10表示文本的总宽度,可以根据需要调整。可以使用<、^、>来分别表示左对齐、居中对齐和右对齐。

0