数字
#整数
print('He got %d marks'%88)
#设置宽度为3,不足0填充
print('He got %03d marks'%95)
#浮点数
print('He got %f marks'% 77.5)
#默认保留3位小数
print('He got %.3f marks'%66.666666)
#保留3位,科学计数法
print('He got %.3e marks'%66.666666)
输入结果如下
He got 88 marks
He got 095 marks
He got 77.500000 marks
He got 66.667 marks
He got 6.667e+01 marks
字符串
s ='This is a test line'
#正常输出
print(s)
#右对齐,占位符20位
print('%20s'%s)
#右对齐,占位符50位
print('%50s'%s)
#左对齐
print('%-s'%s)
#左对齐20位
print('%-20s'%s)
#在字符串中截取8位
print('%.8s'%s)
#右对齐,20位占位符,截取两位
print('%20.2s'%s)
#左对齐,20位占位符,截取两位
print('%-20.2s'%s)
输出结果如下
This is a test line
This is a test line
This is a test line
This is a test line
This is a test line
This is
Th
Th