Python格式化字符串

与C语言类似的格式化

name = 'yucoat'
print 'my name is %s' % name

age = '4.1'
print 'My age is %4.1f' % age
#4:宽度
#1:小数点精确度
#+:必须包含符号,-:左对齐,0,填充0

%(name)s格式化

info = {'name': 'YUCOAT', 'age': 20}
print '%(name)s's age is %(age)d' % info

#用vars()
name = '
YUCOAT'
age = 20
print '
%(name)s's age is %(age)d' % vars()

高级的格式化

format与数字

print 'My name is {0}, my age is {1}'.format('yucoat', 20)

format与字符

print 'My name is {name}, my age is {age}'.format(name = 'YUCOAT', age = 24)

数组与字符的混合

print 'my name is {0}, my age is {age}'.format('YuCoat', age = 24)

format与词典

stock_one = {'Name':'YUCOAT', 'age':42}
stock_two = {'Name':'Thlgood', 'age':34}

print '{0[name] is [1[age]]}'.format(stock_one, stock_two)

x = 3 + 4j
print '{0.real} + {0.imag}'.format(x)

format指定宽度

指定宽度

stock_one = {'Name':'YUCOAT', 'age':42}
print '{name:18} is {age:8}'.format(stock_one)

对齐

stock_one = {'Name':'YUCOAT'}
print 'This is a {0:<20}Heihei'.format(stock_one)  #左对齐
print 'This is a {0:>20}HeiHei'.format(stock_one)  #右对齐
print 'This is a {0:*^20}HeiHei'.format(stock_one) #中间对齐填*
print 'This s a {0:10b}'.format(42)