Python学习笔记之占位符Python %

参考网站:https://www.cnblogs.com/czqq/p/6108557.html

感觉Python学起来有些乱,特别是格式化输出这一块,而格式化输出势必涉及到占位符的使用

今天就来总结一下占位符%的使用

%[(name)][flags][width].[precision]typecode

不要被上面这一大串给吓唬到了,实际上这也是Python的魅力所在

一个个分析

1、(name)属性,它是用来传入字典值的

示例:

print('hi %(name)s' %{'name':'jack'})
结果: hi jack

 

2、[flags]属性,作为用户对一些格式的选择,只有固定的几个值,以下

  • +       右对齐;正数前加正好,负数前加负号;
  • -        左对齐;正数前无符号,负数前加负号;
  • 空格    右对齐;正数前加空格,负数前加负号;
  • 0        右对齐;正数前无符号,负数前加负号;用0填充空白处

示例:

print('the number is %-d %-d' %(+250,-250))
print('the number is %+d %+d' %(+250,-250))
print('the number is %0d %0d' %(+250,-250))
print('the number is % d % d' %(+250,-250))

结果:

the number is 250 -250
the number is +250 -250
the number is 250 -250
the number is 250 -250

 

3、[width]属性,根据名字就可以知道指的是宽度

示例:

print('my salary is %4d yuan in this month' %(2504637))#set the width to four
print('my salary is %9d yuan in this month' %(2504637))#set the width to nine

 

 结果为:

说明如果设置宽度低于实际字符宽度时,会按照实际的宽度来输出

但是如果设置宽度高于字符宽度时,会按照设置的宽度输出,空白符自动补位,右对齐

 

4、.[precision]属性,很简单,与c和c++相似,用来表示输出小数点后几位

示例:

print('the answer to the question is %.3f' % (12.34567))

 

结果为:

the answer to the question is 12.346

这里就不用解释了

 

5、typecod属性,用于指定输出类型

  • s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置
  • r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
  • c,整数:将数字转换成其unicode对应的值,10进制范围为 0 <= i <= 1114111(py27则只支持0-255);字符:将字符添加到指定位置
  • o,将整数转换成 八  进制表示,并将其格式化到指定位置
  • x,将整数转换成十六进制表示,并将其格式化到指定位置
  • d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置
  • e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)
  • E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)
  • f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
  • F,同上
  • g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)
  • G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
  • %,当字符串中存在格式化标志时,需要用 %%表示一个百分号

这里选一个经典示例:

比如想一句话中多种格式化输出,多个占位符 %问题,用个‘+’号就可以解决

print('a is %s ' %('123')+'b is %s'%('456'))
print('the speed of %(obj)s '%{'obj':'light'}+'is %10.2f meters per second' %(299792458))

 

结果:

a is 123 b is 456
the speed of light is 299792458.00 meters per second

这就是%号占位符的总结,谢谢各位看客,觉得好的点个赞哦!!!

转载请注明https://www.cnblogs.com/gambler/p/9567165.html

posted @ 2018-08-31 17:51  沉默的赌徒  阅读(18818)  评论(0编辑  收藏  举报