使用字符串的str.ljust() str.rjust() str.center()
>>> s.ljust(20,"*")
'xyz*****************'
>>> s.rjust(20,"*")
'*****************xyz'
>>> s.center(20,"*")
'********xyz*********'
>>>
使用format() 传递类似’<20’,’>20’,’^20’参数完成任务
>>> format(s,'*>20')
'*****************xyz'
>>> format(s,'*<20')
'xyz*****************'
>>> format(s,'*^20')
'********xyz*********'
>>>
通过实例来应用字符串对齐
将字典中K/V 按照左对齐方式打印出来
d = {'abcdefeg': 123455, 'xyz': 321, 'uvw': 456}
keymax = max([ len(item) for item in (d.iterkeys())])
valuemax = max([len(str(item)) for item in (d.itervalues())])
valuemax = max(map(len,[str(item) for item in d.itervalues()]))
for k,v in d.iteritems():
print "%s %s"%(k.ljust(keymax,"*"),str(v).ljust(valuemax,"-"))
abcdefeg 123455
xyz***** 321---
uvw***** 456---
help(str.ljust/rjust/center/fomrat)
Help on method_descriptor:
rjust(...)
S.rjust(width[, fillchar]) -> string
Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space)
>>> help(str.center)
Help on method_descriptor:
center(...)
S.center(width[, fillchar]) -> string
Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
>>> help(format)
Help on built-in function format in module __builtin__:
format(...)
format(value[, format_spec]) -> string
Returns value.__format__(format_spec)
format_spec defaults to ""