[Tutor] Handling 'None' (null) values when processing sqlite cursorresults

Alan Gauld alan.gauld at btinternet.com
Wed Jul 14 14:32:24 CEST 2010

"Monte Milanuk" <memilanuk at gmail.com> wrote

> (104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin 
> Av.', u'Liberal', u'VT', u'24742', u'1-135-197-1139', 
> u'vehicula.Pellentesque at idmollis.edu', u'2010-07-13 22:52:50', 
> u'2010-07-13 22:52:50')
> At first I was having fits as str.join() was giving me a 'NoneType 
> error'.  I found one way around that, by processing the results so 
> the 'None' values got omitted from the list by the time they got to 
> str.join().

Keep the storage and manipulation of data separate from the
display of that data. That is an important and fundamental principle
of data processing. Store the data with the nulls. Display the data 

> values omitted really messed with the list order which I was 
> depending on i.e. list[5] could be different fields depending on how 
> many 'None'

And that is why.

> values had been omitted.  And if I didn't omit them, when I printed 
> out the user name in the format 'first''middle''last' from the above 
> record,

You need a display function that can strip out the nulls as needed.
A simple list comprehension or generator expression would work
in this case:

print ' '.join(str(field) for field in data if field is not 'None')

If you use a Class to model your data you can write a __str__() method
that does the intellifgent production of a string fit for printing. 
Then you just
print the records as normal. But for this scenario the complexity of 
a class may not be worth it.

The key principle is do not try to store your data in a display 


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list