常用的格式化输出方式1
% 方式
1 print("i am %s my hobby is %s" %("yt","eat"))
打印浮点数,.2表示保留两位。 %%表示打印0 “%” 号
1 print("percent %.2f %%" % 88.5464654) # 结果:88.5464654%
根据字典的键寻值输出
1 print("i am %(name)s my age is %(age)d" %{"name":"yangtuo","age":18})
format 方式拼接字符串
不一一对应则报错
1 tpl = "i am {},age{},{}".format("yangtuo","18","tiancai") 2 print(tpl)
列表元祖按照索引取值,可以不一一对应。直接传列表需要加一个 * 在写列表名
1 tpl = "i am {2},age{0},{1}".format("yangtuo","18","tiancai") 2 print(tpl)
字典用keys来对应,字典必须要加两个 * 在写字典名
1 tpl = "i am {name},age{age},{sb}".format(**{"name":"yangtuo","age":18,"sb":"???"}) 2 print(tpl)
* 表示将内容遍历出来进行取值,:s :d 表示用字符串形式或者整型形式取值
1 tpl = "i am {:s}, age {:d}".format(*["seven", 18]) 2 print(tpl)
b 二进制 ,0 八进制,d 整型,x 16进制,X 大写的16进制,% 显示百分比
1 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%},{}".format(15, 15, 15, 15, 15, 15.87623, 2) 2 print(tpl)
sep="" 添加连接符给多个字符串拼接
1 print("root","x","0","0",sep=":")