Introduction to python's print output text alignment print(%-35s)

1. Problem description

When we use print to print text, we often encounter misalignment problems, making the result look very messy. As shown in the figure below, due to the large difference in the length of the first column of strings, even if I use tabs (\t) to split them, they are not aligned, and there will still be a difference of 1 to 2 \t lengths.
insert image description here

2. Solution

Use the formatted output of print to solve it. print("%-35s\t%s"%(i+':',str(data.attrs[i]))) .

The % here is a placeholder. The placeholder means to use % to occupy a hole in the output, and then use the corresponding variable to fill the hole later. %s indicates that a string type slot is occupied, and a string will be output later; similarly, %d, %f, etc. represent integer type slots and floating point type slots respectively.

You can also add something between % and s to indicate the length of the pit (such as the first placeholder %-35s), and if nothing is added (such as the second placeholder %s), it means no preset Fixed length, output according to the actual length of the string. For example, 35 means that it occupies a pit with a length of 35 characters. If the length of the variable is less than 35, then fill up 35 with spaces, but if the length of the variable is equal to or exceeds 35, then it will be output according to the actual length. Since this 35 is invalid, the effect is equivalent to %s.

In addition, 35 is also divided into positive and negative, which is used to indicate from which side to start filling the hole when the variable is output. If it is 35 (+35), then fill the hole from the right, and later if the length of the variable is not enough for 35, then fill up 35 with spaces on the left, and the effect obtained at this time is right alignment, which is also the default of the computer. And -35 means to fill the hole from the left. If the length of the variable is not enough to 35 later, then fill up 35 with spaces on the right, and the effect obtained at this time is left alignment. But if the length of the variable is equal to or exceeds 35, then it will be output according to the actual length, which means that 35 or -35 is invalid, and the effect is equivalent to %s.

Between two pits, that is, %-35s and %s can also be separated by a symbol, here I use a tab (\t) to separate.

After the pits are set, the pits are filled with variables. The method of filling the hole is to add %() after "%-35s\t%s", and then put variables in order in the brackets, for example, %-35s corresponds to i+':', and %s corresponds to str(data. attrs[i])) . The final result is as shown below.

To sum up, in fact, %-35s can be summarized as left-aligned, with a length of 35, and %s can be summarized as right-aligned, with no length set.

insert image description here

Guess you like

Origin blog.csdn.net/weixin_42999968/article/details/112229720