Python的print()函數可以通過格式化字符串來設置輸出格式。具體的方法有兩種:
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
輸出結果為:
My name is Alice and I am 25 years old.
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
輸出結果為:
My name is Alice and I am 25 years old.
str.format()方法還可以接受多個變量值,例如:
print("My name is {} and my favorite color is {}.".format(name, "blue"))
輸出結果為:
My name is Alice and my favorite color is blue.