python format学习记录

  python中的format方法用于格式化字符串,使用方法:

  1.使用位置来填充字符串内空位:

'{0}{1}'.format('hello','world') #helloworld
'{0}{1}{1}'.format('hello','world') #helloworldworld
'{}{}'.format('hello','world') #helloworld

  若没有标明位置,则按参数的顺序执行,依次替换

  可以重复指定位置参数

  2.列表(list),元组(tuple)内值通过位置来填充字符串内空位

b=["hello","world"]
'{0[0]}{0[1]}'.format(b)
# helloworld

b=("hello","world")
'{0[0]}{0[1]}'.format(b)
# helloworld

  字典不能通过位置来填充字符串内空位

 

  3.使用key来填充字符串内空位

'{a}{b}'.format(a="hello",b="world") #helloworld

  4.列表(list),元组(tuple)和字典(dict)通过key来填充字符串内空位

b=["hello","world"]
'{a[0]}{a[1]}'.format(a=b)
# helloworld

b=("hello","world")
'{a[0]}{a[1]}'.format(a=b)
# helloworld

b={"b1":"hello","b2":"world"}
'{a.b1}{a.b2}'.format(a=b)
# helloworld

  5.使用魔法参数填充字符串内空位

a=['zyc','python']
b={"b1":"hello","b2":"world"}
"{b1} {b2} {0} use {1}".format(*a,**b)
# hello world zyc use python
format(*a,**b) 等于format('zyc','python','b1'='hello','b2'='world') 
在魔法参数中 * 表示列表或元组 **表示字典
  6.使用类属性填充字符串内空位
class A():
    obj='world'
    name='python'
'{a.obj} {a.name}'.format(a=A)
#hello world
{:,} 以逗号分隔数组 1000000 -->1,000,000
{:.2f} 保留2位小数 3.1415926 ---> 3.14
{:+.2f} 保留符号,留2位小数 3.14159 --> +3.14 , -3.14159 -->-3.14
{:b} 转换成2进制
{:x} 转换成16进制
{:o} 转换成8进制
{:d} 转换成10进制
{:0>10} 宽度为10 靠右对齐,剩余用0补齐
{:0<10} 宽度为10 靠左对齐,剩余用0补齐
{:0^10} 宽度为10 中间对齐,剩余用0补齐
{:.2%} 转换为百分制 0.2-->20.00%  
{:.3%} 0.2-->20.000%
   
   
   
   
   


  

 

posted on 2019-08-06 23:06  我已不指望学会编程了  阅读(158)  评论(0)    收藏  举报

导航