3

Background:

When I do data cleaning, I want print my arg name and its value in lines. However args' name vary at length and so do their values. For clarity, I want align arg's name to the left and arg's value to the right in each line.

For instance, I want result like following:

Output:

Arg1               :           value1
Arg2222222222222222:           value2
Arg3               : value33333333333

Current method:

Suppose I have 3 args and 3 values.

name_list = ['Arg1','Arg2222222222222222','Arg3']
value_list = ['value1', 'value2', 'value33333333333']

Using following code, I can print it clearly.

Code:

name_list = ['Arg1','Arg2222222222222222','Arg3']
value_list = ['value1', 'value2', 'value33333333333']
padding1 = max(map(len, name_list))
padding2 = max(map(len, value_list))
print("padding1 = {}, padding2 = {}".format(padding1,padding2))
for num in range(len(name_list)):
    print('{0}: {1}'.format(name_list[num].ljust(padding1), value_list[num].rjust(padding2)))

Output:

padding1 = 19, padding2 = 16
Arg1               :           value1
Arg2222222222222222:           value2
Arg3               : value33333333333

Question:

Can we use less code to achieve the same goal? Or, can we do it more specifically?

Thank you for your help, guys!

Some Citation

String alignment when printing in python

python 3 string formatting (alignment)

J...S
  • 5,079
  • 1
  • 20
  • 35
Travis
  • 1,152
  • 9
  • 25
  • You are doing it just right. Code must not only be efficient but also verbose. The only correction I would suggest for this is that you use f'strings instead of `format`, the former helps readability. – MikeMajara Nov 20 '19 at 11:54

2 Answers2

2

Not much, but if using fstrings, you could do

for name, value in zip(name_list, value_list):
    print(f'{name:<{padding1}}:{value:>{padding2}}')    #fstring version

The < and > are for left and right alignment respectively.

Output will be

Arg1               :          value1
Arg2222222222222222:          value2
Arg3               :value33333333333

See this.

J...S
  • 5,079
  • 1
  • 20
  • 35
2

Using less code, and only missing the separator :

import pandas as pd

name_list = ['Arg1','Arg2222222222222222','Arg3']
value_list = ['value1', 'value2', 'value33333333333']

print(pd.DataFrame(value_list, index=name_list, columns=['']))  # [''] hides the column name (default: 0)

Output:


Arg1                           value1
Arg2222222222222222            value2
Arg3                 value33333333333