如何用定义/非空变量字符串替换%s?或者更确切地说,这样做的Pythonic或语法糖是什么?
示例:
# Replace %s with the value if defined by either vehicle.get('car') or vehicle.get('truck')
# Assumes only one of these values can be empty at any given time
# The get function operates like http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.get
logging.error("Found duplicate entry with %s", vehicle.get('car') or vehicle.get('truck'))
答案 0 :(得分:1)
我想你想要这个:
'Found duplicate entry with %s' % (vehicle.get('car') or vehicle.get('truck'))
这将用非空字符串替换'%s'
(假设只有一个非空字符串)。如果两者都包含文本,则它将替换为vehicle.get('car')
您也可以使用这种类型的字符串格式:
'Found duplicate entry with {0}'.format(vehicle.get('car') or vehicle.get('truck'))
这将返回相同的结果。
答案 1 :(得分:1)
你尝试过这样的事吗?
logging.error("Found duplicate entry with %s" % (vehicle.get('car') or vehicle.get('truck')))
如果truck
也为空,您可以返回默认值:
logging.error("Found duplicate entry with %s" % (vehicle.get('car') or vehicle.get('truck', 'default')))