溫馨提示×

Python中的print函數(shù)怎樣實(shí)現(xiàn)格式化輸出

小樊
121
2024-07-20 06:23:47
欄目: 編程語言

在Python中,print函數(shù)可以使用格式化字符串來實(shí)現(xiàn)格式化輸出。以下是幾種常見的格式化輸出方法:

  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.")

這些方法可以使輸出更加直觀和易讀。您可以根據(jù)自己的喜好和需求選擇其中的一種。

0