Press "Enter" to skip to content

python字符串对齐

对于基本的字符串对齐操作,可以使用字符串的 ljust() , rjust() 和 center() 方法。比如:

>>> text = 'Hello World'
>>> text.ljust(20)
'Hello World         '
>>> text.rjust(20)
'         Hello World'
>>> text.center(20)
'    Hello World     '

所有这些方法都能接受一个可选的填充字符。比如:

>>> text.rjust(20,'=')
'=========Hello World'
>>> text.center(20,'*')
'****Hello World*****'
>>>

如果你想指定一个非空格的填充字符,将它写到对齐字符的前面即可:

>>> format(text, '=>20s')
'=========Hello World'
>>> format(text, '*^20s')
'****Hello World*****'

当格式化多个值的时候,这些格式代码也可以被用在 format() 方法中。比如:

>>> '{:>10s} {:>10s}'.format('Hello', 'World')
'     Hello      World'

下面是一个例子

>>> top_5_domain = [{'key': 'www.hizy.net', 'doc_count': 32109556}, {'key': 'www.xpdo.net', 'doc_count': 12070}, {'key': 'www.zhukun.net', 'doc_count': 1156}, {'key': 'image.baidu.com', 'doc_count': 114}, {'key': 'cloudrea.ksidc.com', 'doc_count': 11}]
>>>
>>> format_temp = "\t {:<20} \t\t {:>12}"
>>> for d in top_5_domain:
...     print(format_temp.format(d["key"],str(d["doc_count"])))
...
     www.hizy.net         		     32109556
     www.xpdo.net         		        12070
     www.zhukun.net       		         1156
     image.baidu.com      		          114
     cloudrea.ksidc.com   		           11

 

Leave a Reply

Your email address will not be published. Required fields are marked *