字符串格式化之——%

 1 # 字符串格式化
 2 msg = 'I am %s , My hobby is %s'%('yuan','play')
 3 print(msg)      # I am yuan , My hobby is play
 4 #打印浮点数
 5 tpl = "percent %.2f" % 99.976234444444444444
 6 print(tpl)      # percent 99.98
 7 #打印百分比
 8 tpl = 'percent %.2f %%' % 99.976234444444444444
 9 print(tpl)      # percent 99.98 %
10 
11 tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}
12 print(tpl)      # i am alex age 18
13 msg='i am %(name)+60s my hobby is alex' %{'name':'lhf'}
14 print(msg)
15 msg='i am \033[43;1m%(name)+60s\033[0m my hobby is alex' %{'name':'lhf'}
16 print(msg)
17 
18 print('root','x','0','0',sep=':')   # root:x:0:0
19 # print('root'+':'+'x'+':'+'0','0')

字符串格式化之——format

 1 # **字典
 2 tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
 3 print(tpl)      # i am seven, age 18, really seven
 4 tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
 5 print(tpl)      # i am seven, age 18, really seven
 6 # *列表
 7 tpl = "i am {:s}, age {:d}".format(*["seven", 18])
 8 print(tpl)      # i am seven, age 18
 9 tpl = "i am {:s}, age {:d}".format("seven", 18) #["seven", 18]
10 print(tpl)      # i am seven, age 18
11 
12 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%},{}".format(15, 15, 15, 15, 15, 15.87623, 2)
13 print(tpl)  # numbers: 1111,17,15,f,F, 1587.623000%,2

 

posted on 2018-03-19 18:06  &&||!  阅读(168)  评论(0编辑  收藏  举报