天天看點

%s

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