如何检查变量是否存在然后在python中打印为字符串

时间:2015-04-14 18:33:10

标签: python google-app-engine google-cloud-datastore

使用GAE的数据存储区我希望打印出一个与变量转换为字符串的语句。 这是我的代码片段,我循环遍历Article种类的所有实体:

    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))

然而,其中一些变量可能不存在。而且我猜这个错误是因为我试图转换Null值?

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

所以我的问题是如何调用if t.likes语句来检查变量是否有值并在同一行连接?

1 个答案:

答案 0 :(得分:1)

如果我是你,我会将输出存储在字符串var中,并且我会在var存在时附加所需的内容:

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)

希望它有所帮助!