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
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Oct 9, 2017 at 19:06
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. 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. 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.

answered Oct 9, 2017 at 20:07
3
  • @xDias not work I get error no attribute to encode.any other idea ? 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 Commented Oct 11, 2017 at 14:00
  • I try some error no attribute to encode Commented Oct 17, 2017 at 13:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.