python print方法怎樣設(shè)置輸出格式

小樊
82
2024-09-25 06:35:11

Python的print()函數(shù)可以通過(guò)格式化字符串來(lái)設(shè)置輸出格式。具體的方法有兩種:

  1. 使用百分號(hào)(%)操作符:在字符串中插入百分號(hào),后面跟上需要輸出的變量名,最后以分號(hào)結(jié)束。例如:
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))

輸出結(jié)果為:

My name is Alice and I am 25 years old.
  1. 使用str.format()方法:在字符串中用大括號(hào){}括起來(lái)需要輸出的變量名,然后調(diào)用str.format()方法將變量值填充到字符串中。例如:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

輸出結(jié)果為:

My name is Alice and I am 25 years old.

str.format()方法還可以接受多個(gè)變量值,例如:

print("My name is {} and my favorite color is {}.".format(name, "blue"))

輸出結(jié)果為:

My name is Alice and my favorite color is blue.

0