Format & End in print in Python

0

I am creating an application that connects to the Sqlite db, search and return the column of the table in question, the problem is that the result returned unformatted looks like this: ( u'Field 1, Field 2' ) , to print I tried to use for within for and printing each field with a print ( '{0} {1} ... '.format ( ... ) ) , and a end = '\n' at the end to be well formatted, but Pyhton does not accept and needs to be very dynamic because the number of items can vary with each db created (the user chooses the fields and the types), I researched a little but I did not find a good way to print this data, I would be grateful if they can send references or explanations.

print ( '{0} {1} ... '.format ( ... ), end = '\n' )

    
asked by anonymous 01.07.2017 / 18:00

1 answer

2

I've adapted this code based on the in this answer .

If your data entry is the values of the columns that were selected in a query. You can format the output regardless of the number of columns specified:

valores = ["gato", "[email protected]", "26", "Vila dos gatos"]

print(' '.join('{}'.format(c) for i, c in enumerate(valores, 1)))

Output:

  

cat [email protected] 26 Cats Street

In this example it uses join and the enumerate function to format the data.

Issue

An adjustment suggested by jsbueno to improve and optimize the routine:

print(' '.join(str(valor) for valor in valores))

Output

  

cat [email protected] 26 Cats Street

Comment from jsbueno:

  

Note that you do not need the enumerate there: it will create a number   corresponding to each item, but you are formatting a string of   each time - then with a single parameter. (If you were to use the   just put "{0}" in the string inside the join). See that you do not even   uses the variable "i" which is where the enumerate value goes. The best there is   simply: print(' '.join(str(valor) for valor in valores)) (already   that goes nothing beyond the value in the string, "str" is shorter than   call the "format" method)

    
01.07.2017 / 19:21