Python的 format
Python的 format 是一种字符串格式化的方法,可以将变量或值插入到字符串中。使用 format 可以让字符串更加灵活和可读性更高。在字符串中,使用花括号 {} 表示要插入的变量或值的位置,然后使用 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.
在 format 中,可以通过花括号中的数字来指定插入的变量或值的顺序。例如:
print("I am {1} years old and my name is {0}.".format(name, age))
输出结果为:
I am 25 years old and my name is Alice.
除了使用数字来指定位置外,还可以使用关键字参数来指定插入的变量或值,例如:
print("I am {age} years old and my name is {name}.".format(name="Alice", age=25))
输出结果为:
I am 25 years old and my name is Alice.
format 还支持格式化输出,可以通过在花括号中加入格式化指令来控制输出的格式,例如:
pi = 3.141592653589793
print("The value of pi is approximately {:.2f}.".format(pi))
输出结果为:
The value of pi is approximately 3.14.
在上面的例子中,"{:.2f}" 表示要输出一个浮点数,保留两位小数。
原文地址: http://www.cveoy.top/t/topic/XXv 著作权归作者所有。请勿转载和采集!