2022年 11月 5日

python3 的输出方法

python3 的输出方法: str.format()

基础用法:

1、默认用法:
	msg = "我叫{},今年{},性别{}".format("大壮", "25", "男")
	print(msg)
	
	输出:
		我叫大壮,今年25,性别男

2、位置用法:下标从0开始
	msg = "我叫{0},今年{1},依然叫{0}".format("大壮", "25")
	print(msg)
	
	输出:
		我叫大壮,今年25,依然叫大壮

3、关键字用法:
	msg = "我叫{name},今年{age},依然叫{name}".format(name = "大壮", age = "25")
	print(msg)
	
	输出:
		我叫大壮,今年25,依然叫大壮
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

实用格式化用法:

可选项':'和格式符可以保证该域至少这么多宽度:
1、可用于位置用法:
msg = "我身高@@{1:10d}@@,体重@@{0:10.3f}@@".format(w = 45.562833585, h =  176)
print(msg)

输出:
	我身高@@       176@@,体重@@    45.563@@

2、可用于关键字用法:
msg = "我身高@@{h:10d}@@,体重@@{w:10.3f}@@".format(w = 45.562833585, h =  176)
print(msg)

输出:
	我身高@@       176@@,体重@@    45.563@@
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

扩展:

1、右对齐(str.format()中默认右对齐),:str.rjust(nums) #不足nums位则右对齐,左补空格
	print("12".rjust(10))
输出:
	        12
2、左对齐:str.ljust(nums) ##不足nums位则左对齐,右边补空格
	print("12".ljust(10))
输出:
	12        #输出到这里了
3、居中:str.center(nums) #不足nums位,则居中,其余位补空格
	print("12".center(10))
输出:
	    12    #输出到这里了
4、左填充0:str.zfill(nums) #不足nums位则右对齐,左不足位填充0
	print("12".zfill(10))
输出:
	0000000012
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

补充:

对于一个列表或字典,str.format()可以使用[]来访问
  ll = ['1', '2', '3']
  print("第{0[0]}位、第{0[2]}位和第{0[1]}位".format(ll))

输出:
  第1位、第3位和第2位
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6