标签:
1.用%s来表示
s = "welcome %s to login %s"%("alex","china") print (s) s = "welcome %(name)s to login %(city)s"%{"name":"alex","city":"wuhan"} print (s)
s = "%10s is %+10d years old"%("alex",-10)
print (s)
alex is -10 years old
解释:第一个字符串占10个字符,右对齐,第二个也占10个字符,右对齐,+号正数前面加+,负数前面加-。
s = "The pi is %.4f"%(3.1415926)
print (s)
The pi is 3.1416
或者是下面的写法
s = "The pi is %(p).4f"%{"p":3.1415926}
s = "The pi is ====%c=====%x======%o"%(65,15,15)
print (s)
The pi is ====A=====f======17
s = "alex %% %%"
print (s)
s1 = "alex %s %%%%"%("SB")
print (s1)
输出:
alex %% %%
alex SB %% #一旦前面出现过%占位符,后面只能用%%表示一个%
2.用format格式化
s = "----->{0}------>{1}------>{0}".format("alex",10) print (s) ----->alex------>10------>alex
s = "----->{name:s}------>{age:d}------>{name:s}".format(name="alex",age=10)
print (s)
----->alex------>10------>alex
s = "-----{:9^20s}=====".format("alex")
print (s)
-----99999999alex99999999=====
解释:字符串宽度为20,居中放置,不足的部分用9来填充
s2 = "======{:*<20s}======{:+d}======{:#b}".format(‘alex‘,123,15)
print (s2)
======alex****************======+123======0b1111
解释:#号只是给b,o,x前面加上0b,0o,0x的符号
s3 = "{:.2%}".format(0.234567)
print (s3)
23.46%
s = "{} is {} years old".format("alex",18)
print (s)
s1 = "{} is {} years old".format(*["alex",18])
print (s1)
s2 = "{name} is {age} years old".format(**{"name":"alex","age":18})
print (s2)
标签:
原文地址:http://www.cnblogs.com/python-study/p/5668710.html