python3字符串的格式化

常用的格式化:

h1 = 'i am %s,my job is %s.'%('th','teacher')            #打印字符串


h2 = 'percent %.2f'% 99.66            #打印浮点数


h3 = 'i am %(name)s age %(age)d'%{'name':'th','age':20}            #字典


h4 = "i am %(pp).2f %%" % {"pp": 88.99, }            #百分数


txt = 'i am \033[42;1m%(name)s\033[0m'%{'name':'th',}            
#改颜色:\033[42;1m%(name)s\033[0m    将'th'改成绿色   


print('root','密码','QQ',sep=':')            #用':'分隔root、密码和QQ


h5 = 'i want to {2},time {1}, people {0}'.format(3,'today','eat')            #format格式化
返回值:i want to eat,time today, people 3


h6 = 'i want to {thing},time {time}, people {number}'.format(thing = 'eat',time = 'today', number = 3)
#和上述结果一样


h7 = 'i want to {thing},time {time}, people {number}'.format(**{'thing': 'eat', 'time': 'today', 'number': 3})
#用字典表示


h8 = 'i want to {:s},time {:s}, people {:d}'.format(*['eat', 'today', 3])
#用列表表示


猜你喜欢

转载自blog.csdn.net/maergaiyun/article/details/82261401