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.