Hướng dẫn python print align columns

I have some code which takes input from the user and stores it in a list. The list may have an odd or even number of elements, for example: my_list = ['Beef','Chicken','Eggs','Lamb','Nuts','Pork'] (even number of elements)

or my_list = ['Beef','Chicken','Eggs','Lamb','Nuts','Pork','Potatoes'] (odd number of elements)

I want to store my_list in a string variable, such so that when I print(var) or create a tkinter messagebox, my program will output two columns like this:

-- Beef       --Chicken
-- Eggs       --Lamb
-- Nuts       --Pork
-- Potatoes

I know how to manipulate the strings, but I'm stuck on creating the columns. I have tried this:

for x,y in zip(my_list[0::2], my_list[1::2]):
    print("{0} {1}".format(x, y))

But that doesn't work for lists of odd-number length. I have also tried the more complicated:

#When my_list = ['Beef','Chicken','Eggs','Lamb','Nuts','Pork','Potatoes']
list1 = []
list2 = []
while len(my_list) != 0:
        list1.append(my_list[0])
        my_list.pop(0)
        if len(my_list) == 0:
            list2.append('')
        else:
            list2.append(my_list[0])
            my_list.pop(0)
    for i in range (len(list1)):
        blank_space = 40 - len(list1[i-1])
        string2 = "\n--" + list1[i] + ' '*blank_space + '--' + list2[i]
        string1 = string1 + string2
    print(string1)

but the output I get is like this:

--Beef                                --Chicken
--Eggs                                    --Lamb
--Nuts                                    --Pork
--Potatoes                                    --

which doesn't align the columns correctly.

Besides splitting it into columns, it is also important that the output is in the form:

--Element1    --Element2
--Element3    --Element4

and not in any other form. I'd really appreciate any help on where I'm making my mistake. If you need anymore clarification just tell me and I will add it into my question.

EDIT: The function will have to work for all these lists:

my_list = ['Beef','Chicken','Eggs','Lamb','Nuts','Pork']
my_list = ['Beef','Chicken','Eggs','Lamb','Nuts','Pork','Potatoes']
my_list = ['Beef','Chicken','Eggs','Lamb','Nuts','Pork','Potatoes','Dairy']
my_list = ['Australian Beef','Chicken','Eggs','Lamb','Nuts','Pork','Potatoes','Dairy']

SECOND EDIT I have finally realized why sometimes it doesn't align. The number of spaces is correct, so all of your answers are correct. Unfortunately because some letters are thinner than others, the columns will not be nicely aligned (at least in Python IDLE and Tkinter). For example, iiii is shorter than mmmm in Python. Is there a way to get around this?

Here is another way how you can format using 'f-string' format:

print(
    f"{'Trades:':<15}{cnt:>10}",
    f"\n{'Wins:':<15}{wins:>10}",
    f"\n{'Losses:':<15}{losses:>10}",
    f"\n{'Breakeven:':<15}{evens:>10}",
    f"\n{'Win/Loss Ratio:':<15}{win_r:>10}",
    f"\n{'Mean Win:':<15}{mean_w:>10}",
    f"\n{'Mean Loss:':<15}{mean_l:>10}",
    f"\n{'Mean:':<15}{mean_trd:>10}",
    f"\n{'Std Dev:':<15}{sd:>10}",
    f"\n{'Max Loss:':<15}{max_l:>10}",
    f"\n{'Max Win:':<15}{max_w:>10}",
    f"\n{'Sharpe Ratio:':<15}{sharpe_r:>10}",
)

This will provide the following output:

Trades:              2304
Wins:                1232
Losses:              1035
Breakeven:             37
Win/Loss Ratio:      1.19
Mean Win:           0.381
Mean Loss:         -0.395
Mean:               0.026
Std Dev:             0.56
Max Loss:          -3.406
Max Win:             4.09
Sharpe Ratio:      0.7395

What you are doing here is you are saying that the first column is 15 chars long and it's left-justified and the second column (values) is 10 chars long and it's right-justified.

If you joining items from the list and you want to format space between items you can use `` and regular formatting techniques.

This example separates each number by 3 spaces. The key here is f"{'':>3}"

print(f"{'':>3}".join(str(i) for i in range(1, 11)))

output:

1   2   3   4   5   6   7   8   9   10

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string.

    Approach : We will be using the f-strings to format the text. The syntax of the alignment of the output string is defined by ‘<‘, ‘>’, ‘^’ and followed by the width number.

    Example 1 : For Left Alignment output string syntax define ‘<‘ followed by the width number.

    print(f"{'Left Aligned Text' : <20}")

    Output :

    Left Aligned Text

    Example 2 : For Right Alignment output string syntax define ‘>’ followed by the width number.

    print(f"{'Right Aligned Text' : >20}")

    Output :

      Right Aligned Text

    Example 3 : For Center Alignment output string syntax define ‘^’ followed by the width number.

    print(f"{'Centered' : ^10}")

    Output :

     Centered 

    Example 4 : Printing variables in Aligned format

    left_alignment = "Left Text"

    center_alignment = "Centered Text"

    right_alignment = "Right Text"

    print(f"{left_alignment : <20}{center_alignment : ^15}{right_alignment : >20}")

    Output :

    Left Text            Centered Text           Right Text
    

    Example 5 : Printing out multiple list values in aligned column look.

    names = ['Raj', 'Shivam', 'Shreeya', 'Kartik']

    marks = [7, 9, 8, 5]

    div = ['A', 'A', 'C', 'B']

    id = [21, 52, 27, 38]

    print(f"{'Name' : <10}{'Marks' : ^10}{'Division' : ^10}{'ID' : >5}")

    for i in range(0, 4):

        print(f"{names[i] : <10}{marks[i] : ^10}{div[i] : ^10}{id[i] : >5}")

    Output :

    Name        Marks    Division    ID
    Raj           7         A        21
    Shivam        9         A        52
    Shreeya       8         C        27
    Kartik        5         B        38