0

%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'))  
4

2 に答える 2

1

私はあなたがこれを望んでいると思います:

'Found duplicate entry with %s' % (vehicle.get('car') or vehicle.get('truck'))

これにより、 が空でない文字列に置き換え'%s'られます (空でない文字列は 1 つだけであると仮定します)。両方にテキストが含まれている場合は、次の出力に置き換えられます。vehicle.get('car')

このタイプの文字列フォーマットを使用することもできます:

'Found duplicate entry with {0}'.format(vehicle.get('car') or vehicle.get('truck'))

これは同じ結果を返します。

于 2013-01-30T08:24:16.987 に答える
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')))
于 2013-01-30T08:24:44.227 に答える