2

I have the latest QGIS 2.18.6 and i try to use some postgis query using python in QGS python console.

field characters from mytable is my non-English language and in postgis have encode 'utf-8' and any time where I want to work In QGIS never haven't problem with characters encode.

but any time to use python and postgis I have any time problem with encode characters.

here the code :

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from qgis.PyQt.QtXml import QDomDocument
from qgis.utils import iface
import psycopg2



constring = u"dbname='database' host='postgre' port='port' user='username' password='code'"
conn=psycopg2.connect(constring)
checkCur = conn.cursor()
sqlCheck = "select * from public.mytable;"
checkCur.execute(sqlCheck)
sqlCheckRess = checkCur.fetchall()

mylist=[]

for i in sqlCheckRess :
    mylist.append(i)
checkCur.close()
conn.close()
print mylist

that work nice but that I take in print mylist is un-humanity language

print like this :

 u'2247_\u03a5\u06c6\u03b9\u04c3\u03c4\u03ac\u05bc\u03b5\u03bd\u03bf \u03c5\u03c0\u03cc\u03b2\u03b1
2
  • Your string is in unicode, and it print very well :s = u'2247_\u03a5\u06c6\u03b9\u04c3\u03c4\u03ac\u05bc\u03b5\u03bd\u03bf \u03c5\u03c0\u03cc\u03b2\u03b1' and print s return me 2247_ΥۆιӃτάּενο υπόβα It's just how the string it's store.
    – SIGIS
    Commented Oct 11, 2017 at 6:36
  • It's how list stores your string and if you print each one of the element it will print as you expect.
    – SIGIS
    Commented Oct 11, 2017 at 7:38

1 Answer 1

1

Try this:

mylist=[]

for i in sqlCheckRess :
    mylist.append([x.encode("utf-8") for x in i])

you are appending unicode objects to the list, that's why you see those un-human characters, have a look at this. Also, I assumed that "i" is a list when you append it.

3
  • @xDias not work I get error no attribute to encode.any other idea ?
    – Mar
    Commented Oct 10, 2017 at 13:48
  • are you getting something like 'list' object has no attribute 'encode'? if so somehow your i object is a list rather than a unicode object. You can try encoding every item on the i list, like this [[x.encode("utf-8") for x in y] for y in i]. Be aware that by doing it this way you'll end up appending a list object to mylist
    – xlDias
    Commented Oct 11, 2017 at 14:00
  • I try some error no attribute to encode
    – Mar
    Commented Oct 17, 2017 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.