赞
踩
本文介绍了Python字符串格式化,主要有两种方法,分享给大家,具体如下
用于字符串的拼接,性能更优。
字符串格式化有两种方式:百分号方式、format方式。
百分号方式比较老,而format方式是比较先进的,企图替代古老的方式,目前两者共存。
1、百分号方式
格式:%[(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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。