aidd

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
统计
 

Python中格式化输出的方式有多种,其中常用的有以下三种:

字符串格式化操作符:使用%对字符串进行格式化,通过指定格式化字符来控制输出的样式。比较常见的格式化字符有:%s表示字符串、%d表示整数、%f表示浮点数等。
例如:

name = "John"
age = 25
score = 95.5

print("My name is %s, I'm %d years old, and my score is %.2f." % (name, age, score))

输出结果为:

My name is John, I'm 25 years old, and my score is 95.50.

str.format()方法:使用str.format()函数将值插入到字符串中。在花括号{}中可以使用字段名、位置索引、格式化字符等进行占位。
例如:

name = "John"
age = 25
score = 95.5

print("My name is {}, I'm {} years old, and my score is {:.2f}.".format(name, age, score))

输出结果为:

My name is John, I'm 25 years old, and my score is 95.50.

f-String:以字母f或F作为前缀,可以在字符串中直接使用表达式来格式化输出,非常方便。
例如:

name = "John"
age = 25
score = 95.5

print(f"My name is {name}, I'm {age} years old, and my score is {score:.2f}.")

输出结果为:

My name is John, I'm 25 years old, and my score is 95.50.

需要注意的是,以上三种方式在实现上都有所不同,具体使用时需要根据场景和个人喜好进行选择和调整。

posted on   开源共享  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
 
点击右上角即可分享
微信分享提示