[Tutor] encode unicode strings from pysqlite

Kent Johnson kent37 at tds.net
Mon Apr 14 12:42:36 CEST 2008


Dinesh B Vadhia wrote:
> Here is a program that SELECT's from a pysqlite database table and 
> encode's the returned unicode strings:

> query = "SELECT fieldB FROM testDB WHERE fieldB LIKE '%s' LIMIT '%s'" 
> %(q, limit)
> for row in cur.execute(query):

Here row is a list containing a single unicode string. When you convert 
a list to a string, it converts the list elements to strings using the 
repr() function. The repr() of a unicode string includes the u'' as part 
of the result.

In [64]: row = [u'99 Cycling Swords']
In [65]: str(row)
Out[65]: "[u'99 Cycling Swords']"

Notice that the above is a string that includes u' as part of the string.

What you need to do is pick out the actual data and encode just that to 
a string.
In [62]: row[0].encode('utf-8')
Out[62]: '99 Cycling Swords'

Kent


More information about the Tutor mailing list