[Tutor] sqlite3 select extra characters

Steven D'Aprano steve at pearwood.info
Fri Jun 18 11:22:52 CEST 2010


On Fri, 18 Jun 2010 03:54:05 pm Lang Hurst wrote:
> Is there a way to just return the values when using sqlite3?
>
> If I:
>
>     names = c.execute('select names from students')
>     for name in names: print names

What is c? A Cursor or a Connection object? It probably doesn't make any 
real difference, but it could, and so you should say.


> I get the list I want, but they look like
>
> (u'Cleese, John')
> (u'Jones, Terry')
> (u'Gillaim, Terry')

I doubt it. Did you mean this?

(u'Cleese, John',)

Note the comma at the end. A subtle difference, but a HUGE one. 
Punctuation is important: it's what makes the difference between:

"Let's eat, Grandma!"

and 

"Let's eat Grandma!"

In Python, the comma makes it a tuple, rather than a meaningless pair of 
parentheses.



> is there a way to just return
>
> Cleese, John
> Jones, Terry
> Gillaim, Terry

No, because you're not *returning* anything, you're *printing*, and 
printing a tuple prints the opening and closing brackets plus the 
repr() of each internal object.

Compare the following:

>>> t = (u"Cleese, John",)  # a tuple like that returned by execute
>>> print t  # print the tuple
(u'Cleese, John',)
>>> print t[0]  # print the unicode string alone
Cleese, John
>>> print repr(t[0])  # print the unicode string's repr()
u'Cleese, John'

This is fundamental stuff: objects are not their printable 
representation, any more than you are a photo of you.

What is printed is not the same as the object itself. Every object has 
its own printable representation. In some cases it looks exactly the 
same as the way you enter the object as a literal:

>>> print 42
42

in other cases it is not:

>>> print "Hello world"
Hello world
>>> print repr("Hello world")
'Hello world'
>>> print "Hello	world"  # includes a tab character
Hello   world
>>> print repr("Hello	world")
'Hello\tworld'


In this case, the object returned by execute is a list of tuples. If 
there is only a single object in each tuple, it is still a tuple, and 
it still prints as a tuple. If you want to print something other than a 
tuple, don't print the tuple:

names = c.execute('select names from students')
for t in names:
    name = t[0]  # Extract the first item from each tuple.
    print name

Of course you can combine the two lines inside the loop:

    print t[0]


> It seems a shame to have to run the answers through a stip process.

It would be more of a shame if execute sometimes returned a list of 
tuples, and sometimes a list of other objects, with no easy way before 
hand of knowing what it would return.



-- 
Steven D'Aprano


More information about the Tutor mailing list