我有一个从文件中读取的字符串列表。每个元素都是一行文件。 我想要一个长度相同的字符串数组。我想找到最长的字符串并重新格式化其他字符串,只要最长的字符串(末尾有空格)。 现在我找到了最长的一个。但我不知道如何重新格式化其他字符串。有人可以帮帮我吗?
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
最佳答案
从这里开始:
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']
关于python - 将列表中的字符串填充为相同长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45120703/