format() 函数可以用于将不同类型的数据插入到字符串中。
下面是几个使用 format() 函数的代码示例:
1. 基本用法:
age = 20
name = "Tom"
print("My name is {0} and I'm {1} years old.".format(name, age))
输出:
My name is Tom and I'm 20 years old.
2. 格式化数字:
pi = 3.1415926
print("The value of pi is approximately {0:.2f}.".format(pi))
输出:
The value of pi is approximately 3.14.
3. 指定宽度和对齐方式:
language = "Python"
print("{0:<10}".format(language)) # 左对齐
print("{0:>10}".format(language)) # 右对齐
print("{0:^10}".format(language)) # 居中对齐
输出:
Python
Python
Python
4. 格式化日期时间:
from datetime import datetime
now = datetime.now()
print("Today's date and time is {:%Y-%m-%d %H:%M:%S}".format(now))
输出:
Today's date and time is 2023-05-05 10:43:59
5. 嵌套使用:
name = "Tom"
age = 20
print("My name is {0} and I'm {1} years old. In {1} years, I will be {2} years old.".format(name, age, age+5))
输出:
My name is Tom and I'm 20 years old. In 20 years, I will be 25 years old.
总之,format() 函数非常灵活,可以用于各种各样的字符串格式化需求。