Python 间距和对齐字符串

问题描述 投票:0回答:8

我正在尝试添加间距以在两个字符串变量之间对齐文本,而不使用

"        "
来这样做

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

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
合作,但没有成功。

建议?

python string alignment
8个回答
86
投票

你应该能够使用格式化方法:

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

您必须根据标签的长度计算出每行的格式长度。

User
线需要比
Location
District
线更宽的格式宽度。


62
投票

尝试使用

%*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

42
投票

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

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

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


35
投票

您可以使用

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

15
投票

@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
投票

复活另一个主题,但这可能对某些人有用。

借助 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

3
投票

Python f 字符串

Python f-string 是用于字符串格式化的最新 Python 语法。 它从 Python 3.6 开始可用。 Python f-string 提供了更快、 更具可读性、更简洁且不易出错的格式化方式 Python 中的字符串。

请访问此处以获取有关字符串格式的详细讨论。

来源:

#!/usr/bin/env python3

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

from datetime import datetime

location = "10-10-10-10"
revision = 1
district = "Tower"
now = datetime.now()
user = "LOD"


width = 30#the width of string

loc = f"Location: {location}"
print(f"{loc: <{width}} Revision: {revision}")

dist = f"District: {district}"
print(f"{dist : <{width}} Date: {now :%b %d, %Y}")

usr = f"User: {user}"
print(f"{usr : <{width}} Time: {now :%H:%M}")

输出:

Location: 10-10-10-10          Revision: 1
District: Tower                Date: Mar 30, 2022
User: LOD                      Time: 12:29

0
投票

有没有办法对间距不均匀的字体(例如 Arial Narrow)执行此操作?

© www.soinside.com 2019 - 2024. All rights reserved.