【python】字符串格式化

1.python字符串格式化 

% 表达式和 format 函数。
format代表字符串格式化的未来。
% 在python的未来版本可能会被抛弃。

--{}表示一个占位符。
vi 2.py 
s="{} is better than {}. {} is better than {}."
a=s.format('Beautiful','ugly','Explicit','implicit')
print(a)

[root@oracle1 python]# python 2.py
Beautiful is better than ugly. Explicit is better than implicit.

--通过下标的方式访问 format 函数的参数。
vi 3.py 
s="{0} is better than {1}. {2} is better than {3}."
a=s.format('Beautiful','ugly','Explicit','implicit')
print(a)

[root@oracle1 python]# python 3.py
Beautiful is better than ugly. Explicit is better than implicit.

--一个参数可以出现多次。
vi 4.py 
s="Beautiful is {0} than ugly. Explicit is {0} than implicit."
a=s.format('better')
print(a)

[root@oracle1 python]# python 4.py
Beautiful is better than ugly. Explicit is better than implicit.

2.namedtuple的使用 

d=dict(good1='Beautiful',bad1='ugly',good2='Explicit',bad2='implicit')
s="{good1} is better than {bad1}. {good2} is better than {bad2}.".format(**d)
print(s)

[root@oracle1 python]# python 5.py
Beautiful is better than ugly. Explicit is better than implicit.

-- format 直接访问对象的属性。
from collections import namedtuple 
Person=namedtuple('Person','name age sex')
xm=Person('shuangqi',20,'male')
s="{p.name}{p.age} old this year".format(p=xm)
print(s)

[root@oracle1 python]# python 6.py
shuangqi20 old this year

format 函数的精度,符号,宽度,对齐方式,字符填充,逗号分隔。

--保留两位小数。
s="{:.2f}".format(3.1415926) #保留2位小数。
print(s)
s1="{:+.2f}".format(3.1415926) #带+号。
print(s1)
s2="{:10.2f}".format(3.1415926) #填充前面满足10位。
print(s2)
s3="{:^10.2f}".format(3.1415926) #满足10位,前后空格填充。
print(s3)
s4="{:_^10.2f}".format(3.1415926) #用_填充直到10位。
print(s4)
s5="{:,}".format(31415926) #按千分割。。
print(s5)
s6="{:_^20,.2f}".format(3.1415926) #保留2位小时,前后填充_;
print(s6)

[root@oracle1 python]# python 7.py
3.14
+3.14
      3.14
   3.14   
___3.14___
31,415,926
________3.14________

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值