how to remove u from sqlite3 cursor.fetchall() in python
import sqlite3
class class1:
def __init__(self):
self.print1()
def print1(self):
con = sqlite3.con开发者_运维问答nect('mydb.sqlite')
cur = con.cursor()
cur.execute("select fname from tblsample1 order by fname")
ar=cur.fetchall()
print(ar)
class1()
gives an output as shown below
[(u'arun',), (u'kiran',), (u'kulku',), (u'sugu',)]
i need to remove u from the array and i need output as shown below
['arun', 'kiran', 'kulku', 'sugu']
If you need that strings retrieved from your sqlite database be returned as UTF-8 instead of Unicode, set-up your connection accordingly using the text_factory propery:
import sqlite3
class class1:
def __init__(self):
self.print1()
def print1(self):
con = sqlite3.connect('mydb.sqlite')
con.text_factory = str
cur = con.cursor()
cur.execute("select fname from tblsample1 order by fname")
ar=cur.fetchall()
print(ar)
class1()
See this for the details: http://docs.python.org/library/sqlite3.html#sqlite3.Connection.text_factory
That takes care of the "u" in front of your strings. You'll then have to convert your list of tuples to a list:
ar=[r[0] for r in cur.fetchall()]
The u
prefix indicates that the string is an Unicode string. If you're sure that the string is a basic ASCII string, you can transform the unicode string into a non-unicode one with a simple str()
.
Example :
unicode_foo = u"foo"
print unicode_foo
>>> u"foo"
print str(unicode_foo)
>>> "foo"
In your case, with a list of tuples, you'll have to do such with a python list comprehension :
ar = [[str(item) for item in results] for results in cur.fetchall()]
Where results
is the list of tuples returned by fetchall
, and item
are the members of the tuples.
the u tells you that these are unicode strings. to print the list of tuples in the format you specified you could use:
>>> myformat="['%s']"%"', '".join([t[0] for t in ar])
>>> print myformat
['arun', 'kiran', 'kulku', 'sugu']
edit:// Example for KIRAN with u and , in the result set:
>>> ar=[(u'u',), (u'u',), (u',,,u,,u,',)]
>>> myformat="['%s']"%"', '".join([t[0] for t in ar])
>>> print myformat
['u', 'u', ',,,u,,u,']
I just add this line and it works
conn.text_factory = str
精彩评论