Print elegantly

1

I want to know how I should print the data on the screen so that it comes out in an "elegant" way, that is to say that each column is shown vertically ordered. I am using the following method:

print("%s: %12i %25.2f "%(string,valor_int,valor_float))

    
asked by Klever Puma 03.12.2017 в 15:40
source

1 answer

0

What happens in your example, is that the "column" corresponding to string is not correctly aligned, so it shifts the entire output. What you can do is something like this:

print("%-20s: %12i %25.2f "%(string,valor_int,valor_float))

Basically we are putting together the formatting options of each value, that of the numbers you have already made, the one of the string is read as follows: - for alignment to the left, 20s defines the output It will be a string with a minimum length of 20 characters. This partially solves the problem, with strings of up to 20 characters will work fine, but being the minimum length, with longer strings we will have a problem:

string= "Esta es una prueba de una cadena bien larga"
valor_int = 15
valor_float = 236.56

print("--------------------- ------------ -------------------------")
print("%-20s: %12i %25.2f "%(string,valor_int,valor_float))

Exit:

--------------------- ------------ -------------------------
Esta es una prueba de una cadena bien larga:           15                    236.56 

The option is to force a clipping of the string to 20 characters using a "slice" like this: string[0:20] :

print("--------------------- ------------ -------------------------")
print("%-20s: %12i %25.2f "%(string[0:20],valor_int,valor_float))

Now the output is more "elegant":

--------------------- ------------ -------------------------
Esta es una prueba d:           15                    236.56 

This way of formatting the data is inherited from Python 2x, although it remains in the new versions, I think it is advisable to tell you to see the new options offered by the language by means of the function format() : Format Specification Mini-Language . It's simple enough to adapt, your example might look something like this:

print("{:<20s}: {:12} {:25.2f} ".format(cadena[0:20],valor_int,valor_float))

On the other hand, if you are looking for a simpler way to handle a tabular output, I recommend the module tabulate

    
answered by 04.12.2017 в 15:43