[Tutor] String representation of NULL (non type) values

Steven D'Aprano steve at pearwood.info
Tue Nov 5 17:37:52 CET 2013


On Mon, Nov 04, 2013 at 11:34:01AM +0100, Ulrich Goebel wrote:
> Hallo,
> 
> from a SQLite database I get a value by SELECT s from... which normaly 
> is a string, but can be the NULL value, wich means it is not defined. To 
> put the value into a form (made by QT) I need a string representation.
> 
> str(s) gives either the string itself (which is good) or "None" (which 
> is not so good) in the case of NULL. Instead of "None" I would prefer an 
> empty string "". How to get that?

if s is None:
    value = ''
else:
    value = str(s)

But since s is already a string (except for the None case), there's no 
need to call str() again.

If you plan of doing this a lot, turn it into a function:

def convert(s):
    if s is None:
        s = ''
    return s


then use it like this:

s = convert(s)


> Possibly there is a build in function smart(s1, s2, s3,...) which 
> returns the first s which is a useable string, or even "" if there isn't 
> any string in the arguments?

No, but it's trivial to make one yourself:

def smart(*args):
    for arg in args:
        if arg is not None:
            return arg
    return ''



-- 
Steven


More information about the Tutor mailing list