How to convert variable to String?

1

I have a function that takes a code from the postgreSQL database and displays it set to QLabel with the function setText() .

The problem is that this code comes from the database in odd format, between parentheses and comma. Example: (VI1,) .

How do I remove these parentheses and commas?

Function:

def cod_via(self,nome_via):
    cursor = self.connectBanco()
    sql = "SELECT cod_via FROM espacial.via WHERE nome_via = '%s'"%nome_via 

    cursor.execute(sql)  
    resultado = cursor.fetchall()                   

    return resultado

I'm displaying with:

cod = instancia_sql.cod_via(nome_via)

self.dlg.label_resul.setText(str(cod))
    
asked by anonymous 14.10.2016 / 21:52

3 answers

0
  

The problem is that this code comes from the database in   strange, in parentheses and comma. Example: (VI1,) . How to remove   these parentheses and commas?

This happens because the method cursor.fetchall() returns a list of tuples, the ideal is to use the cursor.fetchone() , which will return a line or None . See:

def cod_via(self, nome_via):
    cursor = self.connectBanco()
    sql = "SELECT cod_via FROM espacial.via WHERE nome_via = '%s'" % nome_via 

    cursor.execute(sql)
    resultado = cursor.fetchone()

    return resultado
    
14.10.2016 / 23:14
1

If you do not return more than one result you can use join :

return ''.join(resultado)
    
14.10.2016 / 22:54
1

It comes in tuple format.

You can get it like this:

t = ('a', 'b', 1, 2);
t2 = (1, 2, 3, 4, 5, 6, 7 );

print "t[0]: ", t[0]
print "t2[1:5]: ", t2[1:5]

Result:

t[0]:  a
t2[1:5]:  [2, 3, 4, 5]

In your case try cod[0] .

    
14.10.2016 / 22:02