Python间距和对齐字符串

时间:2012-05-16 17:37:20

标签: python string alignment

我正在尝试添加间距以在两个字符串变量之间对齐文本而不使用“”来执行此操作

尝试将文本看起来像这样,第二列对齐。

Location: 10-10-10-10       Revision: 1
District: Tower             Date: May 16, 2012
User: LOD                   Time: 10:15

目前有这样编码,只使用空格......

"Location: " + Location + "               Revision: " + Revision + '\n'

我尝试过使用string.rjust& srting.ljust但无济于事。

建议?

6 个答案:

答案 0 :(得分:56)

您应该可以使用格式化方法:

"Location: {0:20} Revision {1}".format(Location,Revision)

您必须根据标签的长度找出每行的格式长度。用户线需要比位置或区域线更宽的格式宽度。

答案 1 :(得分:37)

尝试%*s%-*s并为每个字符串添加列宽:

>>> print "Location: %-*s  Revision: %s" % (20,"10-10-10-10","1")
Location: 10-10-10-10           Revision: 1
>>> print "District: %-*s  Date: %s" % (20,"Tower","May 16, 2012")
District: Tower                 Date: May 16, 2012

答案 2 :(得分:21)

您可以使用expandtabs指定tabstop,如下所示:

>>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1').expandtabs(30)
>>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012').expandtabs(30)
#Output:
Location:10-10-10-10          Revision: 1
District: Tower               Date: May 16, 2012

答案 3 :(得分:9)

@ IronMensan的格式方法答案是要走的路。但是为了回答你关于ljust的问题:

>>> def printit():
...     print 'Location: 10-10-10-10'.ljust(40) + 'Revision: 1'
...     print 'District: Tower'.ljust(40) + 'Date: May 16, 2012'
...     print 'User: LOD'.ljust(40) + 'Time: 10:15'
...
>>> printit()
Location: 10-10-10-10                   Revision: 1
District: Tower                         Date: May 16, 2012
User: LOD                               Time: 10:15

编辑注意此方法不需要您知道字符串的长度。 .format()也可能,但我不太熟悉它。

>>> uname='LOD'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: LOD                               Time: 10:15'
>>> uname='Tiddlywinks'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: Tiddlywinks                       Time: 10:15'

答案 4 :(得分:6)

从Python 3.6开始,我们有一个更好的选择,f字符串!

>>> print(f"{'Location: ' + location:<25} Revision: {revision}")
>>> print(f"{'District: ' + district:<25} Date: {date}")
>>> print(f"{'User: ' + user:<25} Time: {time}")

输出:

Location: 10-10-10-10     Revision: 1
District: Tower           Date: May 16, 2012
User: LOD                 Time: 10:15

由于大括号中的所有内容都在运行时进行了评估,因此我们可以输入字符串'Location:'和变量location并置。使用:<25将整个串联的字符串放入一个25个字符长的框中,而<表示您希望它保持左对齐。这样,第二列始终在为第一列保留的那25个字符之后开始。

这里的另一个好处是您不必计算格式字符串中的字符。只要25个字符足以容纳左栏中的所有字符,就可以使用25个字符。

https://realpython.com/python-f-strings/解释了f字符串相对于先前选项的好处。 https://medium.com/@NirantK/best-of-python3-6-f-strings-41f9154983e解释了如何使用<,>和^进行左,右和居中对齐。

答案 5 :(得分:0)

复活另一个主题,但这对某些人可能会派上用场。

https://pyformat.info中得到一点启发,您可以构建一种方法来获取目录[TOC]样式的打印输出。

# Define parameters
Location = '10-10-10-10'
Revision = 1
District = 'Tower'
MyDate = 'May 16, 2012'
MyUser = 'LOD'
MyTime = '10:15'

# This is just one way to arrange the data
data = [
    ['Location: '+Location, 'Revision:'+str(Revision)],
    ['District: '+District, 'Date: '+MyDate],
    ['User: '+MyUser,'Time: '+MyTime]
]

# The 'Table of Content' [TOC] style print function
def print_table_line(key,val,space_char,val_loc):
    # key:        This would be the TOC item equivalent
    # val:        This would be the TOC page number equivalent
    # space_char: This is the spacing character between key and val (often a dot for a TOC), must be >= 5
    # val_loc:    This is the location in the string where the first character of val would be located

    val_loc = max(5,val_loc)

    if (val_loc <= len(key)):
        # if val_loc is within the space of key, truncate key and
        cut_str =  '{:.'+str(val_loc-4)+'}'
        key = cut_str.format(key)+'...'+space_char

    space_str = '{:'+space_char+'>'+str(val_loc-len(key)+len(str(val)))+'}'
    print(key+space_str.format(str(val)))

# Examples
for d in data:
    print_table_line(d[0],d[1],' ',30)

print('\n')
for d in data:
    print_table_line(d[0],d[1],'_',25)

print('\n')
for d in data:
    print_table_line(d[0],d[1],' ',20)

结果输出如下:

Location: 10-10-10-10         Revision:1
District: Tower               Date: May 16, 2012
User: LOD                     Time: 10:15


Location: 10-10-10-10____Revision:1
District: Tower__________Date: May 16, 2012
User: LOD________________Time: 10:15


Location: 10-10-... Revision:1
District: Tower     Date: May 16, 2012
User: LOD           Time: 10:15