看一下C語言中的格式化列印
int x = 10;
printf("I am %d years old.", x);
再看下python的樣本
ex05.py
my_name = 'Zed A. Shaw'my_age = 35my_height = 74my_weight = 180my_eyes = 'Blue'my_teeth = 'White'my_hair = 'Brown'print "Let's talk about %s." % my_nameprint "He's %d inches tall." % my_heightprint "He's %d pounds heavy." % my_weightprint "Actually that's not too heavy."print "He's got %s eyes and %s hair." % (my_eyes, my_hair)print "His teeth are usually %s depending on the coffee." % my_teeth# this line is tricky, try to get it exactly rightprint "If I add %d, %d, and %d I get %d." % ( my_age, my_height, my_weight, my_age + my_height + my_weight)print "%(name)s: %(score)06.2f" % {'score':9.5, 'name':'newsim'}print "%(name)s: %(score)6.2f" % {'score':9.5, 'name':'newsim'} print "%(name)r: %(score)r" % {'score':9.5, 'name':'newsim'}
注意:如果你使用了非 ASCII 字元而且碰到了編碼錯誤,記得在最頂端加一行#--coding:utf-8--
。
字串格式化代碼
| 格式 |
描述 |
| %% |
百分比符號標記 |
| %c |
字元及其ASCII碼 |
| %s |
字串 |
| %d |
有符號整數(十進位) |
| %u |
不帶正負號的整數(十進位) |
| %o |
不帶正負號的整數(八進位) |
| %x |
不帶正負號的整數(十六進位) |
| %X |
不帶正負號的整數(十六進位大寫字元) |
| %e |
浮點數字(科學計數法) |
| %E |
浮點數字(科學計數法,用E代替e) |
| %f |
浮點數字(用小數點符號) |
| %g |
浮點數字(根據值的大小採用%e或%f) |
| %G |
浮點數字(類似於%g) |
| %p |
指標(用十六進位列印值的記憶體位址) |
| %n |
儲存輸出字元的數量放進參數列表的下一個變數中 |
| %r |
任何類型 |