温馨提示×

Python中的print函数怎样实现格式化输出

小樊
117
2024-07-20 06:23:47
栏目: 编程语言

在Python中,print函数可以使用格式化字符串来实现格式化输出。以下是几种常见的格式化输出方法:

  1. 使用占位符:%s、%d、%f
name = "Alice"
age = 25
height = 1.65
print("My name is %s, I am %d years old and my height is %.2f meters." % (name, age, height))
  1. 使用.format方法
name = "Alice"
age = 25
height = 1.65
print("My name is {}, I am {} years old and my height is {:.2f} meters.".format(name, age, height))
  1. 使用f-string(Python 3.6及以上版本)
name = "Alice"
age = 25
height = 1.65
print(f"My name is {name}, I am {age} years old and my height is {height:.2f} meters.")

这些方法可以使输出更加直观和易读。您可以根据自己的喜好和需求选择其中的一种。

0