How to concatenate multiple Strings in Python?

The following method c.filtraNome(nome) performs a query in the bank (sqlite3 ), however, I don't know how I can group each field and return the query already formatted as follows:

Nome:  Fulano Silvia
Idade:  19
CPF:  00000000000
Email:  [email protected]
Celular:  1131345678
Cidade:  Nova Vila
UF:  MT
Data do Cadastro:  2015-08-25

I tried concatenating the strings with the operator + and with the method ''.join('String') but did not succeed in any of them.

Query routine:

def filtraNome(self,nome):
        self.db.cursor.execute(""" SELECT * FROM clientes WHERE nome like ? ; """,(['%' + nome + '%']))
        for campo in self.db.cursor.fetchall():
            self.dados = 'Nome: '.join(campo[1]).join('Idade: '.join(campo[2])).join('CPF: '.join(campo[3])).join('Email: '.join(campo[4])).join('Celular: '.join(campo[5])).join('Cidade: '.join(campo[6])).join('UF: '.join(campo[7])).join('Data do cadastro: '.join(campo[8])) #Gera um erro nesta linha.

        return self.dados

The error that is being generated when using the join() method:

self.dados = 'Nome: '.join(campo[1]).join('Idade: '.join(campo[2])).join('CPF: '.join(campo[3])).join('Email: '.join(campo[4])).join('Celular: '.join(campo[5])).join('Cidade: '.join(campo[6])).join('UF: '.join(campo[7])).join('Data do cadastro: '.join(campo[8]))
TypeError: can only join an iterable

Routine calling the method from Class ClienteDB:

if __name__ == '__main__':
    c = ClienteDB()
    if c.cria_tabela():
        print("Tabela %s criada com sucesso.", c.tb_nome)
    #c.inserir_registro()
    #c.listar_todos()
    nome = raw_input("Informe um nome para pesquisa: ")
    print(c.filtraNome(nome))

How can I concatenate the fields returned from the query in Python ?

Author: LINQ, 2015-08-26

2 answers

You must convert your items within campo[indice] to string before trying to concatenate them.

A simple example that would solve the problem (although not recommended) is to use:

'Nome: ' + str(campo[1])

However, Python has several forms for formatting strings. You can read more about it here, here and here .

Some examples of formatting strings

You can use the str.format() method to solve your problem, because it automatically converts to string the data that is passed to it.
A basic method of use, would be:

'Nome: {} Idade: {} CPF: {}'.format(campo[1], campo[2], campo[3])

The keys are replaced by objects passed to the str.format() method, respecting the order of the parameters.

When you have many fields to concatenate, it may be interesting to "number" these parameters, as in the example below:

'Nome: {0} Idade: {1} CPF: {2}'.format(campo[1], campo[2], campo[3])

Here {0} will be replaced by the first parameter of the method and so on (remembering that you do not need to put the campos de formatação in order.

Another interesting way to use this method, especially when you have many fields to format, is to use the parameters with nomes instead of números, as for example:

'Nome: {nome} Idade: {idade} CPF: {cpf}'.format(nome = campo[1], idade = campo[2], cpf = campo[3])
 14
Author: LINQ, 2020-06-11 14:45:34

Python has long had several schemes for formatting strings, with interpolation of data, so that they give the user enough control and separation of what is given and what is code.

That's sure what you want to do - better than concatenate: have a large strign, with the general layout of how you want your output, and interpolate the data read from the database.

Currently (Python 2.7. 3.4) the most recommended way to do this is with the format method of strings. You can even use a string of multiple lines-the ones delimited by triple quotes (""") to create your layout, leaving the serme slots filled by the fields with the markers { }. Since it is a long strign, it is best to use the option that lets you name the component that goes on each marked ({campo}).

In your case, this might be something like:

self.dados = """\
Nome:  {nome}
Idade:  {idade} 
CPF: {cpf}
Email:  {email}
Celular:  {celular}
Cidade:  {cidade}
UF:  {uf}
Data do Cadastro:  {data}""".format(nome=campo[1],idade=campo[2],...,uf=campo[...])

The .format automatically converts the data to its representation as a string-if you don't want it (for example, you want to format a field with decimal numbers with a specific number of boxes), the method has a formatting minilanguage, - letting you specify the type, and decimal numbers after putting : after the field name. Ex.: {total:06.2f} I would say that the " total "would be a numeric field with 6 digits, filled to the left with" 0 and two square after the decimal point. The venerable Luciano Ramalho made a glue card for the Format that is online here: http://python.pro.br/material/cartao-format.pdf - the official documentation is here: https://docs.python.org/2/library/string.html#format-specification-mini-language

Oh, if you check the database connector documentation, you will see that there is a "dictcursor" that brings the columns of your select as a dictionary, rather than ordered in sequence. If you change your code to use dict cursor, you can call the format directly with the query cursor, something like """...""".format(**campos)

 6
Author: jsbueno, 2015-08-27 13:55:41