Kar*_*oki 4 python string list
我有一个从文件中读取的字符串列表.每个元素都是一行文件.我想要一个具有相同长度的字符串数组.我想找到最长的字符串并重新格式化其他字符串,只要最长的字符串(在它们的末尾有空格).现在我发现最长的一个.但我不知道如何重新格式化其他字符串.有人能帮帮我吗?
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
Run Code Online (Sandbox Code Playgroud)
假设您已经从文件中读取了您的字符串列表,您可以使用str.rjust()
填充字符串:
>>> lines = ['cat', 'dog', 'elephant', 'horse']
>>> maxlen = len(max(lines, key=len))
>>>
>>> [line.rjust(maxlen) for line in lines]
[' cat', ' dog', 'elephant', ' horse']
Run Code Online (Sandbox Code Playgroud)
您还可以更改填充中使用的字符:
>>> [line.rjust(maxlen, '0') for line in lines]
['00000cat', '00000dog', 'elephant', '000horse']
>>>
Run Code Online (Sandbox Code Playgroud)
从这开始:
In [546]: array = ['foo', 'bar', 'baz', 'foobar']
Run Code Online (Sandbox Code Playgroud)
使用以下方法查找最大字符串的长度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))
Run Code Online (Sandbox Code Playgroud)
现在,使用列表理解和填充左:
In [551]: [(' ' * (maxlen - len(x))) + x for x in array]
Out[551]: [' foo', ' bar', ' baz', 'foobar']
Run Code Online (Sandbox Code Playgroud)