RWI RWI - 2 months ago 17
Python Question

How to check if variable exist then print as string in python

Using GAE's datastore I wish to print out a statement concatenated with variables turned into string.
This is my codesnippet were I loop through all entities of the

Article
kind:

que = Article.query()

testt = que.fetch(1000)
for t in testt:
self.response.write(t.title)
self.response.write("<b>Artikel:</b> "+t.title + " <b>Forfatter:</b> "+t.author + " <b>Udgivet:</b> "
+ t.time + " <b>Likes:</b> " + str(t.likes) + " <b>Shares:</b> " + str(t.shares) + " <b>Comments:</b> " + str(t.comments))


However some of these variables may not exist. And I'm guessing this error is because I'm trying to convert Null-values?

Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~tipcrawl/1.383603861670919963/main.py", line 134, in get
+ t.time + " <b>Likes:</b> " + str(t.likes) + " <b>Shares:</b> " + str(t.shares) + " <b>Comments:</b> " + str(t.comments))
TypeError: coercing to Unicode: need string or buffer, NoneType found


So my question is how can I call an
if t.likes
statement to check if the variable has a value and concatenate on the same line?

Answer

If I were you, I would store the output in a string var and I will be appending what needed when the var exists:

testt = que.fetch(1000)
for t in testt:
    self.response.write(t.title)
    textToWrite = str()
    if t.title:
        textToWrite += "<b>Artikel:</b> "+ t.title
    if t.author:
        textToWrite += " <b>Forfatter:</b> "+t.author

    # ....
    # and other vars

    #finally, write it
    self.response.write(textToWrite)

Hope it helps!