python中format函数的作用及使用
format函数是Python中用于字符串格式化的方法,可以将一个字符串中的占位符({})替换为指定的值,生成一个新的字符串。
使用方法:
- 位置参数格式化
template = '{} is {} years old'
result = template.format('Tom', 18)
print(result) # 输出 Tom is 18 years old
- 关键字参数格式化
template = '{name} is {age} years old'
result = template.format(name='Tom', age=18)
print(result) # 输出 Tom is 18 years old
- 索引参数格式化
template = '{0} is {1} years old'
result = template.format('Tom', 18)
print(result) # 输出 Tom is 18 years old
- 格式化限定符
template = '{:.2f}'.format(3.1415926)
print(template) # 输出 3.14
其中,.2f 表示保留两位小数,f 表示浮点数类型。
- 格式化元组和字典
template = '{0[name]} is {0[age]} years old'
person = {'name': 'Tom', 'age': 18}
result = template.format(person)
print(result) # 输出 Tom is 18 years old
template = '{name} is {age} years old'
person = {'name': 'Tom', 'age': 18}
result = template.format(**person)
print(result) # 输出 Tom is 18 years old
其中,**person 表示将字典中的键值对解包为关键字参数传入函数中
原文地址: https://www.cveoy.top/t/topic/gSmK 著作权归作者所有。请勿转载和采集!