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: or I want to store
I know how to manipulate the strings, but I'm stuck on creating the columns. I have tried this:
But that doesn't work for lists of odd-number length. I have also tried the more complicated:
but the output I get is like this:
which doesn't align the columns correctly. Besides splitting it into columns, it is also important that the output is in the form:
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:
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, Here is another way how you can format using 'f-string' format:
This will provide the following output:
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}"
output:
View Discussion Improve Article Save Article 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.
Output : Left Aligned Text Example 2 : For Right Alignment output string syntax define ‘>’ followed by the width number.
Output : Right Aligned Text Example 3 : For Center Alignment output string syntax define ‘^’ followed by the width number.
Output : Centered Example 4 : Printing variables in Aligned format
Output : Left Text Centered Text Right Text Example 5 : Printing out multiple list values in aligned column look.
Output : Name Marks Division ID Raj 7 A 21 Shivam 9 A 52 Shreeya 8 C 27 Kartik 5 B 38 |