How to concatenate multiple Strings in Python?

9

The following c.filtraNome(nome) method queries the database (sqlite3), however, I'm not sure how to group each field and return the already formatted query 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 to concatenate the strings with the + operator and the ''.join('String') method, but I 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 method of 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 ?

    
asked by anonymous 26.08.2015 / 20:38

2 answers

12

You should convert your items within campo[indice] to string before attempting to concatenate them.

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

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

However, Python has several ways to format strings . You can read more about this 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 the 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 method parameter and so on (remembering that you do not need to campos de formatação in order.

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

'Nome: {nome} Idade: {idade} CPF: {cpf}'.format(nome = campo[1], idade = campo[2], cpf = campo[3])
    
26.08.2015 / 21:10
5

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

This is certainly what you want to do - rather 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.4.4) the most recommended way to do this is with the format method of strings. You can even use a multi-line string - the triple quotation marks ( """ ) to create your layout, leaving the slots to be populated by the fields with the { } markers. As it is a long strign, it is best to use the option that lets you name the compo that goes in each marked ( {campo} ).

In your case, this could 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[...])

.format automatically converts the data to its representation as a string - if you do not want this (eg you want to format a field with decimal numbers with a specific number of boxes), the method has a miniling formatting, - leaving you specify the type, and decimal place numbers after putting : after the field name. Example: {total:06.2f} would say that the "total" would be a numeric field with 6 digits, filled to the left with "0 and two after the decimal point." The venerable Luciano Ramalho turned a glue card to Format that is online here : link - The official documentation is here: link

Ah, 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 instead of sequentially ordered. If you change your code to use cursor pointer, you can call the direct format with the query cursor line, something like """...""".format(**campos)

    
27.08.2015 / 15:55