1 string="hello" 2 3 #%s打印時結果是hello 4 print "string=%s" % string # output: string=hello 5 6 #%2s意思是字符串長度為2,當原字符串的長度超過2時,按原長度打印,所以%2s的打印結果還是hello 7 print "string=%2s" % string # output: string=hello 8 9 #%7s意思是字符串長度為7,當原字符串的長度小於7時,在原字符串左側補空格, 10 #所以%7s的打印結果是 hello 11 print "string=%7s" % string # output: string= hello 12 13 #%-7s意思是字符串長度為7,當原字符串的長度小於7時,在原字符串右側補空格, 14 #所以%-7s的打印結果是 hello 15 print "string=%-7s!" % string # output: string=hello ! 16 17 #%.2s意思是截取字符串的前2個字符,所以%.2s的打印結果是he 18 print "string=%.2s" % string # output: string=he 19 20 #%.7s意思是截取字符串的前7個字符,當原字符串長度小於7時,即是字符串本身, 21 #所以%.7s的打印結果是hello 22 print "string=%.7s" % string # output: string=hello 23 24 #%a.bs這種格式是上面兩種格式的綜合,首先根據小數點后面的數b截取字符串, 25 #當截取的字符串長度小於a時,還需要在其左側補空格 26 print "string=%7.2s" % string # output: string= he 27 print "string=%2.7s" % string # output: string=hello 28 print "string=%10.7s" % string # output: string= hello 29 30 #還可以用%*.*s來表示精度,兩個*的值分別在后面小括號的前兩位數值指定 31 print "string=%*.*s" % (7,2,string) # output: string= he