Omid
Omid

Reputation: 2677

Why do values from SQLite 3 appear with a "u" prefix? How to hide the prefix

I am trying to learn the basics of SQLite 3. I created a table and tried to print the result:

import sqlite3
def main():
    db = sqlite3.connect('test.db')
    db.execute('drop table if exists test')
    db.execute('create table test (t1 text, i1 int)')
    db.execute('insert into test (t1, i1) values (?, ?)', ('one', 1))
    db.execute('insert into test (t1, i1) values (?, ?)', ('two', 2))
    db.execute('insert into test (t1, i1) values (?, ?)', ('three', 3))
    db.execute('insert into test (t1, i1) values (?, ?)', ('four', 4))
    db.commit()
    cursor = db.execute('select i1, t1 from test order by i1')
    for row in cursor:
        print (row)

if __name__ == "__main__": main()

The print statement works fine but it shows the values like this:

>>> 
(1, u'one')
(2, u'two')
(3, u'three')
(4, u'four')
>>>  

It includes an additional character u (designating a unicode string). How can I print the values without this u prefix?

I noticed that this only happens in Python 2.7, and in Python 3.3.2 it works fine.

Upvotes: 1

Views: 1047

Answers (2)

user2555451
user2555451

Reputation:

You can unpack cursor like so:

for a,b in cursor:
    print a,b

See a demonstration below:

>>> cursor = [(1, u'one'), (2, u'two'), (3, u'three'), (4, u'four')]
>>> for a,b in cursor:
...     print a,b
...
1 one
2 two
3 three
4 four
>>>

Upvotes: 2

Steinar Lima
Steinar Lima

Reputation: 7821

I would suggest you just do

for row in cursor:
        print(row[0], row[1])

That being said, I doubt that you are running Python 3.x.

print((1, u'aaa'))

Yields

(1, 'aaa')

on Python 3.3, and

(1, u'aaa')

on Python 2.7.

Upvotes: 1

Related Questions