欢迎访问宙启技术站
智能推送

format函数格式化输出文本

发布时间:2023-09-14 07:26:53

format() 函数是 Python中内置的一个函数,用于格式化输出文本。它接受一个模板字符串作为参数,并使用传入的值进行替换。

format() 函数的语法是:

formatted_string = "模板字符串".format(值1, 值2, ...)

在模板字符串中,用大括号 {} 来表示要插入值的位置。大括号内可以使用索引或关键字来指定要插入的值。

下面是使用 format() 函数的一些常见用法:

1. 使用位置参数:

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.

2. 使用索引参数:

name = "Bob"
age = 30
print("My name is {0}, and I am {1} years old.".format(name, age))

输出结果:My name is Bob, and I am 30 years old.

3. 使用关键字参数:

name = "Charlie"
age = 35
print("My name is {name}, and I am {age} years old.".format(name=name, age=age))

输出结果:My name is Charlie, and I am 35 years old.

4. 使用索引和关键字混合参数:

name = "David"
age = 40
print("My name is {0}, and I am {age} years old.".format(name, age=age))

输出结果:My name is David, and I am 40 years old.

5. 控制输出格式:

x = 3.1415926
print("The value of pi is {:.2f}".format(x))

输出结果:The value of pi is 3.14

在这个例子中,:.2f 表示要显示两位小数的浮点数。

format() 函数还支持更多的格式化选项,如对齐、填充、进制转换等,具体可以参考 Python 官方文档中的格式化字符串语法。使用 format() 函数可以灵活地格式化输出任意类型的数据,并且可以减少代码中的重复和硬编码。