您现在的位置:小学生自学网>> 信息>> python辅导

python中format的基本用法

作者: 来源: 发布时间:2024年01月27日 点击数:
 

ormat 基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

format基本用法

 
print("Hello {0} {1}".format("Chen","xin") # 引用第一个参数
# 输出 'Hello Chen xin'
 
print("{} is cute".format("Chen xin") # 引用第一个参数
# 输出 'Chen xin is good'
 
print("My name is {name}".format(name="Chen xin") # 引用名字为name的参数
# 输出 'My name is Chen xin'
 
 
通过位置来填充字符串
 
print('{0}, {1}, {2}'.format('a', 'b', 'c')) # a, b, c
print('{}, {}, {}'.format('a', 'b', 'c')) # a, b, c
print('{2}, {1}, {0}'.format('a', 'b', 'c')) # c, b, a
print('{2}, {1}, {0}'.format(*'abc')) # c, b, a
print('{0} {1} {0}'.format('aa', 'bb')) # aa bb aa