python格式化输出

% 方式

 

语法格式


%[(name)][flags][width].[precision]typecode

常用示例


# tpl = "i am %s" % "yangge"
# print(tpl)
# tpl = "i am %s age %d" % ("yangge", 18)
# print(tpl)
# tpl = "i am %(name)s age %(age)d" % {"name":
"yangge", "age": 18}
# print(tpl)
# tpl = "percent %.2f" % 99.97623
# print(tpl)
# tpl = "i am %(pp).2f" % {"pp": 123.425556, }
# print(tpl)
tpl = "i am %.2f%%" % 123.425556
print(tpl)

format 方式


[[fill]align][#][0][width][,][.precision][type]

常用示例


tpl = "i am {}, age {}, {}"
r = tpl.format("yangge", 18, 'yangge')
print(r)
tpl = "i am {}, age {}, {}"
r = tpl.format(*["yangge", 18, 'yangge'])
print(r)
a, *b = ["yangge", 18, 'yangge']
print(a)
print(b)
*b, a = ["yangge", 18, 'ge']
print(a)
print(b)
tpl = "i am {0}, age {1}, really {0}"
print(tpl.format("xiguatian", 18))
tpl = "i am {0}, age {1}, really {0}"
tpl.format(*["xiguatian", 18])
tpl = "i am {name}, age {age}, really {name}"print(tpl.format(name="xiguatian", age=18))
#
tpl = "i am {name}, age {age}, really {name}"
print(tpl.format(**{"name": "xigatian", "age":
18}))
tpl = "i am {0[0]}, age {0[1]}, really {1[2]}"
print(tpl.format([1, 2, 3], [11, 22, 33]))
tpl = "i am {:s}, age {:d}, money {:f}"
print(tpl.format("seven", 18, 88888.1))
tpl = "i am {:s}, age {:d}".format(*["seven",
18])
print(tpl)
tpl = "i am {name:s}, age {age:d}"
tpl.format(name="xiguatian", age=18)
tpl = "i am {name:s}, age {age:d}"
tpl.format(**{"name": "xiguatian", "age": 18})
tpl = "numbers: {:b},{:o},{:d},{:x},{:X},
{:%}"
print(tpl.format(15, 15, 15, 15, 15, 15.87623,
2))
tpl = "numbers: {0:b},{0:o},{0:d},{0:x},
{0:X},\
{0:.2%}"
print(tpl.format(15))tpl = "numbers: {num:b},{num:o},{num:d},
{num:x},\
{num:X}, {num:.2%}"
print(tpl.format(num=15))
print("{0:.3%}".format(0.15))
tpl = "{:<10}{:<8}{:>3}"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值