我有一个从文件读取的字符串列表。每个元素都是一行文件。我想要一个长度相同的字符串数组。我希望找到最长的字符串,并将其他字符串重新格式化为与最长字符串一样长的字符串(在它们的末尾加上空格)。现在我找到了最长的一个。但我不知道如何重新格式化其他字符串。有谁能帮帮我吗?
with open('cars') as f:
    lines = f.readlines()
lines = [line.rstrip('\n') for line in open('cars')]
max_in=len(lines[0])
for l in lines:
    print (str(len(l))+" "+str(max_in))
    if max_in < len(l):
        max_in=len(l)
print max_in发布于 2017-07-16 01:05:38
从这个开始:
In [546]: array = ['foo', 'bar', 'baz', 'foobar']使用max查找最大字符串的长度
In [547]: max(array, key=len) # ignore this line (it's for demonstrative purposes)
Out[547]: 'foobar'
In [548]: maxlen = len(max(array, key=len))现在,使用列表理解并向左填充:
In [551]: [(' ' * (maxlen - len(x))) + x for x in array]
Out[551]: ['   foo', '   bar', '   baz', 'foobar']发布于 2017-07-16 01:12:49
假设已经从文件中读取了字符串列表,可以使用str.rjust()填充左侧的字符串:
>>> lines = ['cat', 'dog', 'elephant', 'horse']
>>> maxlen = len(max(lines, key=len))
>>> 
>>> [line.rjust(maxlen) for line in lines]
['     cat', '     dog', 'elephant', '   horse']您还可以更改填充中使用的字符:
>>> [line.rjust(maxlen, '0') for line in lines]
['00000cat', '00000dog', 'elephant', '000horse']
>>> 发布于 2017-07-16 01:06:28
1)查找max len:
max_len = max(len(el) for el in lines)2)在其他字符串的末尾添加空格:
lines = [" "*(max_len - len(el)) + el for el in lines]https://stackoverflow.com/questions/45120703
复制相似问题