Python的format()函数是用来格式化字符串的方法。它可以在字符串中插入变量、常量或表达式,并指定它们的格式。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.
print("My name is {0} and I am {1} years old.".format(name, age))
输出:My name is Alice and I am 25 years old.
print("My name is {name} and I am {age} years old.".format(name="Bob", age=30))
输出:My name is Bob and I am 30 years old.
pi = 3.14159
print("The value of pi is {:.2f}".format(pi))
输出:The value of pi is 3.14
print("My name is {0:10} and I am {1:03d} years old.".format("Alice", 5))
输出:My name is Alice and I am 005 years old.
format()函数可以根据数据类型自动选择格式化选项,如浮点数的精度、整数的进制等。使用format()函数可以实现复杂的字符串格式化需求,并提高代码的可读性。