对齐
^、<、>分别是居中、左对齐、右对齐,后面带宽度,例如
#右对齐
str = "{:@>8}".format("123")
print(str) #@@@@@123
#左对齐
str = "{:@<8}".format("123")
print(str) #123@@@@@
#居中对齐
str = "{:@^8}".format("123")
print(str) #@@123@@@
数字格式化
print( "今天是{0}号,温度是{1:.2f}℃".format(28,26.3))
#今天是28号,温度是26.30℃
其它格式如下
填入字符串
1、使用0,1,2,3...来占位,数字可以重复使用
#使用0,1,2,3...来占位,数字可以重复使用
str = "今天的天气是{0},很适合{1},我喜欢{0}"
str = str.format('晴天','学习')
print(str) #今天的天气是晴天,很适合学习,我喜欢晴天
2、使用{参数名}来映射参数值,将字符串格式化
#使用{参数名}来映射参数值,将字符串格式化
str = "今天的天气是{weather},很适合{action},我喜欢{weather}"
str = str.format(action = '学习',weather = '晴天')
print(str) #今天的天气是晴天,很适合学习,我喜欢晴天