1

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.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Omid
  • 2,617
  • 4
  • 28
  • 43
  • Also http://stackoverflow.com/questions/2464959/whats-the-u-prefix-in-a-python-string – Michael Berkowski Jan 03 '14 at 03:33
  • I know what it means, I just don't want it to appear in the print statement. So this question is different. – Omid Jan 03 '14 at 03:36
  • @novice66: It's appearing because you're printing a `tuple` object, not a string. The tuple object represents its contents using `repr` instead of `str`. – Blender Jan 03 '14 at 03:41

2 Answers2

2

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
>>>
Community
  • 1
  • 1
1

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.

Steinar Lima
  • 7,644
  • 2
  • 39
  • 40