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

后端 未结 4 1065
情歌与酒
情歌与酒 2021-02-13 04:19
import sqlite3
class class1:
def __init__(self):
    self.print1()
def print1(self):
    con = sqlite3.connect(\'mydb.sqlite\')
    cur = con.cursor()
    cur.execute(\"         


        
相关标签:
4条回答
  • 2021-02-13 04:50

    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,']
    
    0 讨论(0)
  • 2021-02-13 04:59

    I just add this line and it works

    conn.text_factory = str
    
    0 讨论(0)
  • 2021-02-13 05:02

    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()]
    
    0 讨论(0)
  • 2021-02-13 05:02

    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.

    0 讨论(0)
提交回复
热议问题