Python学习笔记-占位符“%”

Python学习笔记-占位符%

参考网址原创位于 https://www.cnblogs.com/gambler/p/9567165.html

首先看看格式:

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

不要被上面这一大串给吓唬到了,实际上这也是Python的魅力所在,现在我们一个个分析:

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

示例:

print('hello_ %(name)s' %{'name':'jack'})
结果: hello_ 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 % d % d' %(+250,-250))
print('the number is %0d %0d' %(+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

结果:
my salary is 2504637 yuan in this month  # 注意如果设置宽度低于实际字符宽度,会按照实际的宽度来输出
my salary is   2504637 yuan in this month #但是如果设置宽度高于字符宽度时,会按照设置的宽度输出,空白符自动补位,右对齐

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

示例:

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

结果:
the answer to the question is 12.346

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

  • 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('String is string:%s ' %(1234)+'INT is %d'%(5678))
print('the speed of %(obj)s '%{'obj':'light'}+'is %-18.2f meters per second' %(299792458))
print('the speed of %(obj)s '%{'obj':'light'}+'is %+18.2f meters per second' %(299792458))
结果:

String is string:1234 INT is 5678
the speed of light is 299792458.00       meters per second
the speed of light is      +299792458.00 meters per second
# %(obj)s为占位符+(name)属性,name为字典键在后面传入字典键值对方便取值;%12.2f占位符+18位整数和两位小数,同时-18前‘-’符号使对齐方式未左对齐后面自动补齐空格;-18前‘+’符号使对齐方式未右对齐后面自动补齐空格并在正数前加正号;



posted @ 2021-04-21 12:55  zechariah1  阅读(651)  评论(0编辑  收藏  举报