1. 程式人生 > >python 4-5 如何對字串進行左, 右, 居中對齊str.ljust/rjust/center/format(s,'20'/'^20')

python 4-5 如何對字串進行左, 右, 居中對齊str.ljust/rjust/center/format(s,'20'/'^20')

python 4-5 如何對字串進行左, 右, 居中對齊str.ljust/rjust/center/format(s,’<20’/’>20’/’^20’)
解決方案:
使用字串的str.ljust() str.rjust() str.center()
使用format() 傳遞類似’<20’,’>20’,’^20’引數完成任務

使用字串的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 ""