나는 바로 가기이에 거기에이"foo {}"형식의 파이썬 사전 문자열에 조건부 문자열을 추가하는 방법이 있습니까? 예를 들어
if checked:
checked_string = "check"
else:
checked_string = "uncheck"
print "You can {} that step!".format(checked_string)
과 같은 코드의 라인을 가지고? 나는 단지 궁금했다.
내가 아는나는 바로 가기이에 거기에이"foo {}"형식의 파이썬 사전 문자열에 조건부 문자열을 추가하는 방법이 있습니까? 예를 들어
if checked:
checked_string = "check"
else:
checked_string = "uncheck"
print "You can {} that step!".format(checked_string)
과 같은 코드의 라인을 가지고? 나는 단지 궁금했다.
내가 아는print "You can {} that step!".format('check' if checked else 'uncheck')
checkmap = {True: 'check', False: 'uncheck'}
print "You can {} that step!".format(checkmap[bool(checked)]))
, 나는 매우 늦었 어. 그러나 사람들은 수색을합니다.
필자는 사용자가 제공 한 구성의 일부인 형식 문자열이 가능한 한 단순해야하는 상황에서이를 사용하고 있습니다. 즉, 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.
와우 나는 if-then과 같은 출력을 선언 할 수 있는지조차 몰랐습니다. – hobbes3
@ hobbes3 : 그건 그렇다면 아니에요. 그것은 Python (bass-ackwards) 삼항 연산자입니다. –
모두가 왜 그렇게 싫어하는지 잘 모르겠다 ... C/Java 구문에 익숙해지면 매우 논리적 인 것처럼 보인다. – jamylak