2012-04-13 2 views

답변

16
print "You can {} that step!".format('check' if checked else 'uncheck') 
+0

와우 나는 if-then과 같은 출력을 선언 할 수 있는지조차 몰랐습니다. – hobbes3

+2

@ hobbes3 : 그건 그렇다면 아니에요. 그것은 Python (bass-ackwards) 삼항 연산자입니다. –

+4

모두가 왜 그렇게 싫어하는지 잘 모르겠다 ... C/Java 구문에 익숙해지면 매우 논리적 인 것처럼 보인다. – jamylak

5
checkmap = {True: 'check', False: 'uncheck'} 
print "You can {} that step!".format(checkmap[bool(checked)])) 
2

, 나는 매우 늦었 어. 그러나 사람들은 수색을합니다.

필자는 사용자가 제공 한 구성의 일부인 형식 문자열이 가능한 한 단순해야하는 상황에서이를 사용하고 있습니다. 즉, Python에 대해 전혀 알지 못하는 사람들이 작성했기 때문입니다.

이 기본 형식에서는 하나의 조건으로 만 사용이 제한됩니다.

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.