舊方法
Python2.6之前,格式字串的使用方法相對更簡單些,雖然其能夠接收的參數數量有限制。這些方法在Python3.3中仍然有效,但已有含蓄的警告稱將完全淘汰這些方法,目前還沒有明確的時間進度表。
格式化浮點數:
pi = 3.14159 print(" pi = %1.2f ", % pi)
#多個替換值:
##
s1 = "cats" s2 = "dogs" s3 = " %s and %s living together" % (s1, s2)
set = (%s, %s, %s, %s, %s, %s, %s, %s) " % (a,b,c,d,e,f,g,h,i)
set = set = " ({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}) ".format(a,b,c,d,e,f,g)
Python 2.x 基於字典字串格式化
"%(n)d %(x)s" %{"n":1, "x":"spam"} reply = """ Greetings... Hello %(name)s! Your age squared is %(age)s """ values = {'name':'Bob', 'age':40} print rely % values
#Python 3.x format方法格式化
template = '{0},{1} and {2}' template.format('spam','ham','eggs') template = '{motto}, {pork} and {food}' template.format(motto='spam', pork='ham', food='eggs') template = '{motto}, {0} and {food}' template.format('ham', motto='spam', food='eggs') '{motto}, {0} and {food}'.format(42, motto=3.14, food=[1,2,3])