파이썬에서 템플릿 문자열 내에 의사 - 삼항 연산자를 구현하려고합니다. kwargs
에 특정 키가 있으면 값이 문자열에 삽입됩니다.re.sub()에 kwargs를 전달하십시오.
re
모듈에는 정확히 re.sub()
에서 필요한 것을 수행하는 방법이 있으며, 일치하는 함수를 호출 할 수 있습니다. 내가 할 수없는 일은 **kwargs
을 전달하는 것입니다. 코드
import re
template_string = "some text (pseudo_test?val_if_true:val_if_false) some text"
def process_pseudo_ternary(match, **kwargs):
if match.groups()[0] in kwargs:
return match.groups()[1]
else:
return match.groups()[2]
def process_template(ts, **kwargs):
m = re.compile('\((.*)\?(.*):(.*)\)')
return m.sub(process_pseudo_ternary, ts)
print process_template(template_string, **{'pseudo_test':'yes-whatever', 'other_value':42})
라인 if match.groups()[0] in kwargs:
가 비어 process_pseudo_ternary의 kwargs
으로, 과정의 문제가 따른다.
전달 방법에 대한 아이디어가 있으십니까? m.sub(function, string)
은 인수를 사용하지 않습니다.
마지막 문자열은 some text val_if_true some text
(사전에 'pseudo_test'키가 있기 때문에)입니다.
문자열에서 3 진수 연산자의 다른 구현으로 자유롭게 이동하십시오. 나는 Python conditional string formatting을 알고 있습니다. 문자열의 형식화 튜플/딕트가 아닌 문자열에 삼진이 있어야합니다. 내가 제대로 이해한다면
맞음! 그게 soves, 하루 동안 기다릴 것입니다 (있다면) 어떤 대답이 공정한, 그래도, 감사합니다 – bartekbrak