How to concatenate multiple Strings in Python?

Asked

Viewed 70,082 times

11

The following method c.filtraNome(nome) carry out a consultation at the bank (sqlite3), however, I don’t know how I can group each field and return the already formatted query in the following way:

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 with the method ''.join('String') but I was unsuccessful in any of them.

Routine that performs the query:

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 being generated when using the method join():

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 class method 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?

  • which error is generated on the line ?

  • This mistake: Typeerror: can only Join an iterable

  • Join only works with arrays or "things that can be iterated"... with '+' gives some error ?

  • Yes with more also returns an error, in the last record "Data: " + campo[8], the two are returning error.

  • is probably giving an "index out of range"... I’m seeing that you started picking up the array fields from Indice 1... but the array starts at 0.. That’s right ?

  • The zero index and the id I don’t show him.

  • What’s the mistake you’re making then? Do the following... to avoid a "conversation" in the comments, edit your question by putting more details, showing what approaches you used and what errors were when you used them.

  • @Denercarvalho, try concatenating using Nome: + str(campo[1])... and let me know the result so I can post it as an answer. I really think that’s the problem.

Show 3 more comments

2 answers

16


You must convert your items into campo[indice] for 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 method str.format() 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])

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

When you have many fields to concatenate, it can 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 an example:

'Nome: {nome} Idade: {idade} CPF: {cpf}'.format(nome = campo[1], idade = campo[2], cpf = campo[3])
  • 1

    Thanks for the help, this way it worked, I managed to separate the values and group them.

7

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

This is sure 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. 3.4) the most recommended way to do this is with the method format strings. You can even use a multiple-line string - those bounded by triple quotes (""") to create your layout, leaving the slots to be filled 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 on 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[...])

The .format automatically converts the data to its representation as a string - if you do not want this (for example, you want to format a field with decimal numbers with a specific number of houses), the method has a formatting mini-language, - letting you specify the type, and decimal numbers after placing : after the field name. Ex. : {total:06.2f} I’d say the "total" would be a six-digit numeric field, filled left with "0 and two squares after the decimal point. The venerable Luciano Ramalho created a glue card for the Format that is online here: http://python.pro.br/material/cartao-format.pdf - The official document is here: https://docs.python.org/2/library/string.html#format-Specification-mini-language

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

  • Thanks for the explanation!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.