python中print格式化输出的方法是什么

227
2024/2/29 20:06:50
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Python中print函数的格式化输出可以通过占位符的方式实现。常用的占位符有:

  • %s:字符串
  • %d:整数
  • %f:浮点数

示例如下:

name = "Alice"
age = 20
height = 1.65
print("Hello, my name is %s, I am %d years old and %.2f meters tall." % (name, age, height))

另外,Python3.6及以上版本还支持使用f字符串进行格式化输出,示例如下:

name = "Alice"
age = 20
height = 1.65
print(f"Hello, my name is {name}, I am {age} years old and {height:.2f} meters tall.")

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 怎么在Python中遍历集合