64

我正在尝试添加间距以对齐两个字符串 vars 之间的文本而不使用" "这样做

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

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但无济于事。

建议?

4

6 回答 6

79

您应该能够使用格式方法:

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

您必须根据标签的长度计算出每行的格式长度。该User行将需要比LocationorDistrict行更宽的格式宽度。

于 2012-05-16T17:45:17.897 回答
58

尝试%*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
于 2012-05-16T17:46:40.217 回答
31

您可以使用expandtabs来指定制表位,如下所示:

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

输出:

Location: 10-10-10-10         Revision: 1
District: Tower               Date: May 16, 2012
于 2012-05-16T17:47:51.463 回答
24

从 Python 3.6 开始,我们有一个更好的选择,f-strings!

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。Using:<25将整个连接的字符串放入一个 25 个字符长的框中,并<指定您希望它左对齐。这样,第二列总是在为第一列保留的 25 个字符之后开始。

这里的另一个好处是您不必计算格式字符串中的字符。使用 25 将适用于所有这些,前提是 25 的长度足以包含左列中的所有字符。

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

于 2020-07-08T20:17:00.687 回答
14

@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'
于 2012-05-16T18:26:38.667 回答
4

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

从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
于 2019-07-03T19:48:12.153 回答