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