温馨提示×

python print方法怎样设置输出格式

小樊
82
2024-09-25 06:35:11
栏目: 编程语言

Python的print()函数可以通过格式化字符串来设置输出格式。具体的方法有两种:

  1. 使用百分号(%)操作符:在字符串中插入百分号,后面跟上需要输出的变量名,最后以分号结束。例如:
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.
  1. 使用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.

0