python中format的用法是什么

695
2023/12/4 12:41:13
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,format()方法用于格式化字符串。它是一个内置的字符串方法,可以通过占位符来指定字符串中的值。

格式化语法如下:

string.format(value1, value2, ...)

其中,string是要进行格式化的字符串,value1, value2, … 是要插入到字符串中的值。

格式化字符串中的占位符使用一对大括号 {} 来表示,可以在占位符中指定值的格式。

以下是一些常见的格式化示例:

  1. 简单的占位符
name = "Alice"
age = 20
print("My name is {} and I am {} years old".format(name, age))

输出:My name is Alice and I am 20 years old

  1. 指定值的类型
value = 3.14159
print("The value of pi is {:.2f}".format(value))

输出:The value of pi is 3.14

  1. 指定占位符的顺序
name = "Bob"
age = 25
print("My name is {1} and I am {0} years old".format(age, name))

输出:My name is Bob and I am 25 years old

这只是format()方法的一些基本用法示例,它还支持更多的功能,如对齐、填充、格式化数字、日期等。详细的用法可以参考Python官方文档。

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

推荐阅读: python中字符串常用的内建函数有哪些