码迷,mamicode.com
首页 > 编程语言 > 详细

python之字符串格式化

时间:2020-01-25 11:47:23      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:ring   bsp   输出   报错   mat   family   font   style   print   

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%

python之字符串格式化

标签:ring   bsp   输出   报错   mat   family   font   style   print   

原文地址:https://www.cnblogs.com/cxydnxs/p/12232902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!