[英]Templates with argument in string formatting
我正在尋找字符串格式內的模板的軟件包或其他任何方法(手動替換除外)。
我想要實現這樣的功能 (這只是一個示例,所以您可以了解其主意,而不是實際的工作代碼):
text = "I {what:like,love} {item:pizza,space,science}".format(what=2,item=3)
print(text)
因此輸出將是 :
I love science
我該如何實現? 我一直在搜索,但找不到合適的東西。 可能使用了錯誤的命名術語。
如果周圍沒有任何准備使用的軟件包,我很想閱讀一些起點來自己編寫代碼。
我可以使用列表或元組作為what
和item
因為這兩種數據類型都保留插入順序。
what = ['like', 'love']
item = ['pizza', 'space', 'science']
text = "I {what} {item}".format(what=what[1],item=item[2])
print(text) # I like science
甚至有可能。
text = "I {what[1]} {item[2]}".format(what=what, item=item)
print(text) # I like science
希望這可以幫助!
我認為使用列表就足夠了,因為python列表是持久的
what = ["like","love"]
items = ["pizza","space","science"]
text = "I {} {}".format(what[1],items[2])
print(text)
輸出:我喜歡科學
為什么不使用字典?
options = {'what': ('like', 'love'), 'item': ('pizza', 'space', 'science')}
print("I " + options['what'][1] + ' ' + options['item'][2])
這將返回:“我愛科學”
或者,如果您想要一種擺脫格式重新設置以容納/刪除空間的方法,那么可以將其合並到字典結構中,如下所示:
options = {'what': (' like', ' love'), 'item': (' pizza', ' space', ' science'), 'fullstop': '.'}
print("I" + options['what'][0] + options['item'][0] + options['fullstop'])
然后返回:“我喜歡披薩。”
由於沒有人提供合適的答案來直接回答我的問題,所以我決定自己解決這個問題。
我必須使用雙括號,因為單引號保留用於字符串格式化。
我完成了以下課程:
class ArgTempl:
def __init__(self, _str):
self._str = _str
def format(self, **args):
for k in re.finditer(r"{{(\w+):([\w,]+?)}}", self._str,
flags=re.DOTALL | re.MULTILINE | re.IGNORECASE):
key, replacements = k.groups()
if not key in args:
continue
self._str = self._str.replace(k.group(0), replacements.split(',')[args[key]])
return self._str
這是一個原始的,五分鍾的書面代碼,因此缺少檢查等。 它可以按預期工作,並且可以輕松改進。
在Python 2.7和3.6上測試過
用法:
test = "I {{what:like,love}} {{item:pizza,space,science}}"
print(ArgTempl(test).format(what=1, item=2))
> I love science
感謝您的所有答復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.