本文介紹了Python字符串格式化,主要有兩種方法,分享給大家,具體如下
用于字符串的拼接,性能更優(yōu)。
字符串格式化有兩種方式:百分號(hào)方式、format方式。
百分號(hào)方式比較老,而format方式是比較先進(jìn)的,企圖替代古老的方式,目前兩者共存。
1、百分號(hào)方式
格式:%[(name)][flags][width].[precision]typecode
>>> s = 'i am %s,age %d' %('cai',18)
>>> print(s)
i am cai,age 18
>>> s = 'i am %(n1)s,age %(n2)d' %{'n1':'cai','n2':18}
>>> print(s)
i am cai,age 18
>>> s = 'i am %(n1)+10s,age %(n2)d' %{'n1':'cai','n2':18}
>>> print(s)
i am cai,age 18
>>> s = 'i am %(n1)+10s,age %(n2)10d' %{'n1':'cai','n2':18}
>>> print(s)
i am cai,age 18
>>> s = "i am %.3f abcd" %1.2
>>> print(s)
i am 1.200 abcd
2、format方式、
i1 = "i am {},age {} ,{}".format('cairui',18,'kk')
print(i1)
i am cairui,age 18 ,kk
i1 = "i am {0},age {1} ,{0}".format('cairui',18)
print(i1)
i am cairui,age 18 ,cairui
i1 = "i am {name},age {age} ,{name}".format(name='cairui',age=18)
print(i1)
i am cairui,age 18 ,cairui
i1 = "i am {:s},age {:d} ,{:f}".format('cairui',18,6.1)
print(i1)
i am cairui,age 18 ,6.100000