Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad strings to be the same length in a list

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
like image 406
Karim Pazoki Avatar asked Nov 28 '22 22:11

Karim Pazoki


2 Answers

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']
like image 95
cs95 Avatar answered Dec 05 '22 13:12

cs95


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']
>>> 
like image 25
Christian Dean Avatar answered Dec 05 '22 13:12

Christian Dean