how to remove u from sqlite3 cursor.fetchall() in

2019-03-24 08:20发布

import sqlite3
class class1:
def __init__(self):
    self.print1()
def print1(self):
    con = sqlite3.connect('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']

3条回答
forever°为你锁心
2楼-- · 2019-03-24 08:55

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,']
查看更多
The star\"
3楼-- · 2019-03-24 09:03

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.

查看更多
迷人小祖宗
4楼-- · 2019-03-24 09:12

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()]
查看更多
登录 后发表回答