如何在Python中打印NoneType对象?
# score can be a NonType object
logging.info("NEW_SCORE : "+score)
Run Code Online (Sandbox Code Playgroud)
另外为什么有时候我会看到一个逗号而不是上面的+?
最好的方法是:
logging.info("NEW_SCORE: %s", score)
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,您必须%在左侧的格式字符串和右侧的值(在元组中,如果多于一个)之间使用运算符.但是logging函数是特殊的:你将格式字符串作为第一个参数传递,然后,一个接一个地传递,与所需的参数一样多,以匹配%s格式中的&c格式标记的数量,并且logging函数将使用格式化运算符%s作为适当的,当且仅在必要时 - 如果您当前的日志记录级别(例如,logging.info实际上不会显示),则不会产生任何运行时开销.
无论如何忘记str调用和+基于字符串的连接 - 即使没有logging特殊内容,%-formatting确实是要走的路(在Python 2.6或更早版本中;在2.6或更高版本中,你也应该考虑字符串的format方法,允许更清晰和更易读的表达式什么相同的功能).
logging.info("NEW_SCORE : " + str(score))
Run Code Online (Sandbox Code Playgroud)
Python解释器的证明:
>>> x = None
>>> "x: " + x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'NoneType' objects
>>> "x: " + str(x)
'x: None'
Run Code Online (Sandbox Code Playgroud)
QED