阅读量:0
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.
- 使用str.format()方法:在字符串中用大括号{}括起来需要输出的变量名,然后调用str.format()方法将变量值填充到字符串中。例如:
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.