python-使字符串在一列中从左边恰好排成 n 个空格

python-making strings line up in a column exactly n spaces from left

在python中,有没有一种方法可以将字符串打印到文件中,使其正好距离最左边的列有n个空格?例如,我在文件中有以下几行:

fname1 lname1 ID1 num1
fname2 mname2 lname2 ID2 num2
fname3 mname3 lname3 ID3 num3

我希望所有名字(名字、姓氏,可能还有中间名)都在宽度为 20 的列中,所有名字都在最左边。然后我希望所有 ID 都位于宽度为 10 的列中,所有 ID 都位于该宽度为 10 的列的最左侧,最后我希望所有数字都位于宽度为 10 的列中,以便所有 IDS在宽度为 10 的列的最左侧。

例如,输出应该是:

fname1 lname1             ID1       num1
fname2 mname2 lname2      ID2       num2
fname3 lname3             ID3       num3

我尝试使用

line=inpf.readline()
parts=line.split()
line_size=len(parts)
for i in range(0,line_size-2):                                                                                  
    outf.write(parts[i]+' ')
outf.write('{0:>20}'.format(ID))

但这只会使 ID 成为 lname.

右侧的 20 个空格

我不确定你是如何处理 name 的,但我认为这应该符合你最初的问题。

st1 = fname + ' ' + lname
outf.write(st)
ln1 = len(st)

if ln1 > 20:
    do something acc to your requirement

st2 = ' ' * (20-ln) + ID
outf.write(st2)

ln2 = ln1 + len(st2)
if ln2 > 30:
    do something acc to your requirement

st3 = ' ' * (30-ln2) + num1
outf.write(st3)

来自对问题的评论:

i want all the names to be in a column of width 20, and all the fnames to be on the very left of that column of width 20, all the ids to be in a column of width 10, with all the ids on the very left of that column of width 10, and then all the nums to in a column of width 10, with all the nums on the very left of that column of width 10

这让这变得容易多了。

row = "{:20}{:10}{:10}"  # build formatter string

with open('path/to/file.txt') as inf:
    lines = [line.split() for line in inf]

for fname, mname, lname, id, num in lines:
    col1 = ' '.join([fname, mname, lname])
    col2 = id
    col3 = num
    print(row.format(col1, col2, col3))

在 Python3 中,您可以通过以下方式优雅地处理缺少的中间名:

for *names, id, num in lines:
    print(row.format(' '.join(names), id, num))