cikatomo
cikatomo

Reputation: 1631

parentheses when printing list

This is not sqlite specific, but it I wondered while learning python and sqlite3 and listing the results of query. I have simple code:

connection = sqlite3.connect("db.sqlite")
cursor = connection.cursor()
cursor.execute("select * from db")
print cursor.fetchall()

So, the results of the print cursor.fetchall() is: [(u'koko',), (u'lolo',)] But, when I try to recreate that kind of print with this code:

i=["koko","lolo"]
print i

the print result is: ['koko', 'lolo']

Two things I don't understand:

  1. why the first list has 'u' for unicode when printing and second doesn't?
  2. why the first list has parenthesis (u'koko',) when printing and second doesn't?

Is the first list a list of tuples maybe?

Upvotes: 1

Views: 2005

Answers (3)

juankysmith
juankysmith

Reputation: 12458

You may want to manipulate the results to adapt it to the format you want...

rows = cursor.fetchall()
result = [elem[0] for elem in rows]

...and maybe to apply a function to elem[0] (depending on your python version) to put the strings in the format you want to.

Upvotes: 2

Pavel Anossov
Pavel Anossov

Reputation: 62958

[(u'koko',), (u'lolo',)] is a list of 1-element tuples of unicode strings.

["koko","lolo"] is a list of byte strings.

Upvotes: 3

mgilson
mgilson

Reputation: 310297

The list has parenthesis because that is how python prints a tuple.

Contrast:

a = 'foo'
print a,type(a)

with:

b = ('foo',)
print b,type(b)

Also note that in python2.x, there are different types of strings. unicode is just a type of string, and python chooses to represent that as u'whatever':

>>> print u'whatever'
whatever
>>> print repr(u'whatever')
u'whatever'

Note that str(tup) implicitly calls repr on each element in the tuple.

Upvotes: 3

Related Questions