#字符串格式规约
#format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
#参数详解
#fill ::= ,填充字符
#align ::= "<" | ">" | "^"左对齐,右对齐,右对齐
#sign ::= "+" | "-" | " "数字是否带正负标识
#width ::= integer 长度
#precision ::= integer 小数位数
#type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" 类型
s="This is a test string";
print("{0}".format(s));
print("{0:>25}".format(s));
print("{0:^25}".format(s));
print("{0:<25}".format(s));
print("{0:.10}".format(s));
print("{0:*=12}".format(8749203));
print("{0:*=12}".format(-8749203));
print("{0:*>12}".format(8749203));
print("{0:*^12}".format(8749203));
print("{0:*<12}".format(8749203));
print("b:{0:b},0:{0:0},x:{0:x},X:{0:X})".format(8749203));
print("{0:,}".format(8749203));
import math;
amout=(10**3)*math.pi
print("[{0:12.2e}],[{0:12.2f}]".format(amout));
print("[{0:*<12.2e}],[{0:#<12.2f}]".format(amout));
#个人感觉以下例子比较完全,所以直接转载过来。
print('{0}, {1}, {2}'.format('a', 'b', 'c'))
print('{}, {}, {}'.format('a', 'b', 'c') ) # 3.1+ only
print('{2}, {1}, {0}'.format('a', 'b', 'c'))
print('{2}, {1}, {0}'.format(*'abc')) # unpacking argument sequence
print( '{0}{1}{0}'.format('abra', 'cad'))
print('Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W'))
coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
print('Coordinates: {latitude}, {longitude}'.format(**coord))
coord = (3, 5)
print('X: {0[0]}; Y: {0[1]}'.format(coord))
print("repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2'));
print('{:<30}'.format('left aligned'))
print('{:>30}'.format('right aligned') )
print('{:^30}'.format('centered'))
print('{:*^30}'.format('centered')) # use '*' as a fill char
print('{:+f}; {:+f}'.format(3.14, -3.14)) # show it always
print('{: f}; {: f}'.format(3.14, -3.14) ) # show a space for positive numbers
print('{:-f}; {:-f}'.format(3.14, -3.14) )# show only the minus -- same as '{:f}; {:f}'
print("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42))
# with 0x, 0o, or 0b as prefix:
print("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42))
points = 19
total = 22
print('Correct answers: {:.2%}.'.format(points/total))
for align, text in zip('<^>', ['left', 'center', 'right']):
print('{0:{fill}{align}16}'.format(text, fill=align, align=align))