RWI RWI - 1 year ago 104
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


que = Article.query()

testt = que.fetch(1000)
for t in testt:
self.response.write("<b>Artikel:</b> "+t.title + " <b>Forfatter:</b> " + " <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/", 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/", 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/", 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/", line 1102, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/", line 572, in dispatch
return self.handle_exception(e,
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/", line 570, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~tipcrawl/1.383603861670919963/", 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 Source

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:
    textToWrite = str()
    if t.title:
        textToWrite += "<b>Artikel:</b> "+ t.title
        textToWrite += " <b>Forfatter:</b> "

    # ....
    # and other vars

    #finally, write it

Hope it helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download