python之字符串格式化

1.string=‘my name is %s , my age is 18‘ % ‘gtl‘

   print(string)                           //输出结果为my name is gtl ,my age is 18

   s=‘my name is %s ,my age is %s‘ % (‘alex‘,18) 

   print(s)                                  //输出结果为my name is alex ,my age is 18

2.s=‘number is %.2f ‘ % 99.956489999

   print(s)                                  //输出结果为number is 99.96 ,打印浮点数

3.s=‘my name is %(name).3s ,my age is %(age)d ‘ % {‘name‘:‘xtf‘,‘age‘:20}

   print(s)                                  //输出结果为my name is xtf ,my age is 20

4.s=‘my name is {} ,my age is {}‘.format(‘hg‘,20)

   print(s)                                  //输出结果为my name is hg,my age is 20,不一一对应则报错

   string=‘my name is {name},my age is {age}‘.format(name=‘hg‘,age=18)

   print(string)                         //输出结果为my name is hg,my age is 18

   s=‘my name is {name},my age is {age}‘.format(**{‘name‘:‘lbb‘,‘age‘:28})

   print(s)                                //输出结果为my name is lbb,my age is 28

   s=‘my age is {0[1]},her age is {1[2]}‘.format([18,19,20],[21,22,23])

   print(s)                               //输出结果为my age is 19,her age is 23

   s=‘my name is {:s},my age is {:d}‘.format(*[‘eight‘,29])

   print(s)                                //输出结果为my name is eight,my age is 29

   s=‘number : {:b},{:o},{:x},{:X},{:%}‘.format(15,15,15,15,15.8697)

   print(s)                                //输出结果为num : 1111,17,f,F,1586.970000%

相关推荐