`format` 是 Python 中的一个字符串格式化函数,用于将变量或表达式的值插入到字符串中,并控制插入值的格式。`format` 函数的基本语法是使用花括号 `{}` 作为占位符,并通过冒号 `:` 和其他字符指定格式化方式。
1. 基本格式化:
s = "{} is a {}".format('Tom', 'Boy')
print(s) 输出:Tom is a Boy
2. 指定位置:
s = "{} is a {}".format('Tom', 'Boy', 'Girl')
print(s) 输出:Tom is a Boy
3. 指定格式:
s = "{:.2f} is a {:.1f}".format(3.14159, 2.71828)
print(s) 输出:3.14 is a 2.7
4. 命名参数:
s = "{name} is a {gender}".format(name='Tom', gender='Boy')
print(s) 输出:Tom is a Boy
`format` 函数非常灵活,可以处理不同类型的数据,并且可以自定义格式化方式,因此在 Python 开发、数据爬虫等领域广泛应用