我正在拉入带有占位符的文本字符串作为实例属性。我正在尝试编写一些内容来获取占位符文本,找到具有该名称的属性,然后将其交换。我能够获取该属性,但要交换它,我必须对占位符进行硬编码.
“new_text_string = ...”行给了我“KeyError:'dntier'” 下面的注释行有效,但我不想对每个可能的属性进行硬编码。
import re
class Test:
def __init__(self,mdtier,rxtier,dntier,vstier):
self.mdtier = mdtier,
self.rxtier = rxtier,
self.dntier = dntier,
self.vstier = vstier,
rec = Test('You Only','You Only','You + Family','You + Spouse')
text_string = 'Dental coverage for {dntier}.'
try:
text_variable = re.search('\{(.+?)\}', text_string).group(1)
except AttributeError:
text_variable = ''
if text_variable:
replacement = getattr(rec, text_variable)[0]
new_text_string = text_string.format(text_variable=replacement)
#new_text_string = text_string.format(dntier=replacement)
else:
new_text_string = text_string
这似乎是一种非常复杂的方法,否则应该是简单的字典查找,假设我理解你所追求的内容。这对你有用吗?
def get_coverage(tier: str) -> str:
coverage_tiers = {
'md': 'You Only',
'rx': 'You Only',
'dn': 'You + Family',
'vs': 'You + Spouse',
}
coverage = coverage_tiers.get(tier, None)
if coverage is None:
return f'"{tier}" is not a valid coverage tier'
return f'Dental coverage for {coverage}.'
print(get_coverage('md'))
print(get_coverage('dn'))
print(get_coverage('not a valid key'))
# EXAMPLE OUTPUT:
# >>> Dental coverage for You Only.
# >>> Dental coverage for You + Family.
# >>> "not a valid key" is not a valid coverage tier
这里我定义了一个
coverage_tiers
的字典和一个简单的函数来访问该字典中的字符串值。