使用字符串的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 ""
本文介绍Python中字符串对齐方法str.ljust(), str.rjust(), str.center()及format()函数的应用。通过实例展示了如何使用这些方法进行字符串格式化,并提供了一种按指定宽度左对齐、右对齐和居中对齐的方法。此外还展示了如何通过格式化字典中的键值对来生成整齐的输出。

2733

被折叠的 条评论
为什么被折叠?



