I have a list of strings that read from file. Each element is a line of file. I want to have an array of this string that have same length. I want to find the longest string and reformat other strings as long as longest string (with space at the end of them). Now I find the longest one. but I don't know how can I reformat other strings. Can anybody help me please?
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
Starting with this:
In [546]: array = ['foo', 'bar', 'baz', 'foobar']
Find the length of the largest string using 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))
Now, use a list comprehension and pad left:
In [551]: [(' ' * (maxlen - len(x))) + x for x in array]
Out[551]: [' foo', ' bar', ' baz', 'foobar']
Assuming you have your list of strings already read from the file, you can use str.rjust()
to pad your strings left:
>>> lines = ['cat', 'dog', 'elephant', 'horse']
>>> maxlen = len(max(lines, key=len))
>>>
>>> [line.rjust(maxlen) for line in lines]
[' cat', ' dog', 'elephant', ' horse']
You can also change the character used in the padding:
>>> [line.rjust(maxlen, '0') for line in lines]
['00000cat', '00000dog', 'elephant', '000horse']
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With