3.1415926 {:.2f} 3.14 保留小数点后两位

3.1415926 {:+.2f} +3.14 带符号保留小数点后两位

-1 {:+.2f} -1.00 带符号保留小数点后两位

2.71828 {:.0f} 3 不带小数

5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)

5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)

10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)

1000000 {:,} 1,000,000 以逗号分隔的数字格式

0.25 {:.2%} 25.00% 百分比格式

1000000000 {:.2e} 1.00e+09 指数记法

13 {:10d}        13 右对齐 (默认, 宽度为10)

13 {:<10d} 13 左对齐 (宽度为10)

13 {:^10d}    13 中间对齐 (宽度为10)

string.format()基础

s1 = "so much depends upon {}".format("a red wheel barrow") s2 = "glazed with {} water beside the {} chickens".format("rain", "white")

s1 = " {0} is better than {1} ".format("emacs", "vim") s2 = " {1} is better than {0} ".format("emacs", "vim")

Python2.6之前，格式字符串的使用方法相对更简单些，虽然其能够接收的参数数量有限制。这些方法在Python3.3中仍然有效，但已有含蓄的警告称将完全淘汰这些方法，目前还没有明确的时间进度表。[PEP-3101]

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)

format()函数提供了相当多的附加特性和功能，如下是一些有用的使用.format()的技巧。

madlib = " I {verb} the {object} off the {place} ".format(verb="took", object="cheese", place="table") >>> I took the cheese off the table

str = "Oh {0}, {0}! wherefore art thou {0}?".format("Romeo") >>> Oh Romeo, Romeo! wherefore art thou Romeo?

print("{0:d} - {0:x} - {0:o} - {0:b} ".format(21)) >>> 21 - 15 - 25 -10101