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)