2

たとえば、次のようなコード行があります

if checked:
    checked_string = "check"
else:
    checked_string = "uncheck"

print "You can {} that step!".format(checked_string)

これへのショートカットはありますか?ちょっと気になっただけ。

4

4 に答える 4

20
print "You can {} that step!".format('check' if checked else 'uncheck')
于 2012-04-13T04:10:42.377 に答える
5
checkmap = {True: 'check', False: 'uncheck'}
print "You can {} that step!".format(checkmap[bool(checked)]))
于 2012-04-13T04:06:28.217 に答える
2

私は知っています、私は非常に遅れています。しかし、人々は検索します。

フォーマット文字列はユーザ​​ーが提供する構成の一部であるため、つまり、Python について何も知らない人によって記述されているため、フォーマット文字列をできるだけ単純にする必要がある状況でこれを使用しています。

この基本形では、使用は 1 つの条件に限定されます。

class FormatMap:
    def __init__(self, value):
        self._value = bool(value)

    def __getitem__(self, key):
        skey = str(key)
        if '/' not in skey:
            raise KeyError(key)
        return skey.split('/', 1)[self._value]

def format2(fmt, value):
    return fmt.format_map(FormatMap(value))

STR1="A valve is {open/closed}."
STR2="Light is {off/on}."
STR3="A motor {is not/is} running."
print(format2(STR1, True))
print(format2(STR2, True))
print(format2(STR3, True))
print(format2(STR3, False))

# A valve is closed.
# Light is on.
# A motor is running.
# A motor is not running.
于 2016-08-11T15:56:06.607 に答える