Python格式化

#encoding=utf-8
'''
字符串格式化:将字符串根据自己需求进行任意的拼接
由于字符串是不可变的,尽量不要用+进行拼接,它会不断开辟内存空间,效率低

1、常用格式化 % :
格式:%[(name)][flags][width].[precision]typecode
      (name):可选,指定key值
      flags:可选(+:右对齐,正数前面加正号;负数前面加负号;
                   -:左对齐,正数前面无符号;负数前面加负号;
                 空格:右对齐,正数前面加空格;负数前面加负号;
                  0:右对齐,正数前面无符号;负数前面加负号;用0填充空白处)
      width:可选,占用宽度
      .precision:可选,小数后面保留位数
      typecode:必选(s,d,f)

%s : 万能传递,可以传递任何对象(包括原子和容器),正常都用%s
%d : 只能传递数字,其他类型会报错
%f :浮点数 (默认保留6位)
    % .2f :浮点数,保留2位小数,第三位进行四舍五入
%.2f %%:百分比

2、通过print(s1,s2,s3...,sep=":")进行拼接  s1:s2:s3...

3、format()方法字符串拼接 传字典用**开头,传的是列表或元组用*开头;:s表示字符串,:d表示数字
    *表示遍历可迭代对象,将可迭代对象的元素提取使用

    tp1 = "i am {0},age {1},really {0}".format("高淇",19)
    tpl = "i am {names},age {ages}".format(names="高淇",ages=19)
#传递字典用**开头
    tpl = "i am {names},age {ages}".format(**{"names":"高淇","ages":19})
    tpl = "i am {0[0]},age {0[1]},really {0[2]}".format([1,2,3],[4,5,6])
    tpl = "i am {:s},age {:d},really {:f}".format("seven",19,888.8172)
#传递列表或元组用*开头
    tpl = "i am {:s},age {:d},really {:f}".format(*["seven",19,888.8172])
    tpl = "i am {:s},age {:d},really {:f}".format(*("seven",19,888.8172))
    tpl = "i am {names:s},age {ages:d}".format(names="高淇",ages=19)
    tpl = "i am {names:s},age {ages:d}".format(**{"names":"高淇","ages":19})

    tpl = "number:{:b},{:o},{:d},{:x},{:X},{:%}".format(15,15,15,15,15,15.87234,2)

'''
# 打印字符串  s可以接收任何值(字符串、数字、列表等)
msg = "i am %s my hobby is alex"%"lhf"
print(msg)
''' i am lhf my hobby is alex '''

msg = "i am %s my hobby is %s"%("lhf",1)
print(msg)
''' i am lhf my hobby is 1 '''

msg = "i am %s my hobby is %s"%("lhf",(1,2,3))
print(msg)
''' i am lhf my hobby is (1, 2, 3) '''

#打印浮点数 %f 默认保留6位小数,最后一位四舍五入
tpl = "percent %f"%99.65435677
print(tpl)
''' percent 99.654357 '''

tpl = "percent %.2f"%99.65435677
print(tpl)
''' percent 99.65 '''

#打印百分比
tpl = "percent %.2f%%"%99.65435677
print(tpl)
''' percent 99.65% '''

#通过键的方式进行字符串的拼接
tpl = "i am %(name)s age %(age)d"%{"name":"alex","age":19}
print(tpl)
''' i am alex age 19 '''

#使用可选参数
tpl =  "i am %(name)+20s age %(age)d"%{"name":"alex","age":19}
print(tpl)
''' i am                 alex age 19 '''

#通过print()进行拼接
print("root","125","0","0","123",sep=":")
'''  root:125:0:0:123   '''


#format()方法的使用
tpl = "number:{:b},{:o},{:d},{:x},{:X},{:.2%}".format(15,15,15,15,15,15.87234,2)
print(tpl)
''' number:1111,17,15,f,F,1587.23% '''

猜你喜欢

转载自www.cnblogs.com/linan-8888/p/12966653.html