对大量替换字段使用.format()

2024-09-28 18:50:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含许多替换字段的长字符串,然后用以下格式进行格式化:

firstRep  = replacementDict['firstRep']
secondRep = replacementDict['secondRep']
.
.
.
nthRep    = replacementDict['nthRep']

newString = oldString.format(firstRep = firstRep, 
                             secondRep = secondRep,...,
                             nthRep = nthRep)

有没有一种方法可以避免必须单独设置每个选项并使用循环方法?在

谢谢。在


Tags: 方法字符串format格式选项newstringoldstringreplacementdict
3条回答

您可以unpack argument dicts with a ^{} prefix

newString = oldString.format(**replacementDict)

使用^{},它是为这个用例提供的

old_string.format_map(replacement_dict)

注意:format_map仅在python3.2+中提供。在python2中,您可以使用**解包(参见this相关问题),hower这会迫使python复制字典,因此速度会慢一点,并使用更多内存。在

你可以这样简单地解包字典

replacementDict = {}
replacementDict["firstRep"]  = "1st, "
replacementDict["secondRep"] = "2nd, "
replacementDict["thirdRep"]  = "3rd, "

print "{firstRep}{secondRep}{thirdRep}".format(**replacementDict)
# 1st, 2nd, 3rd, 

引用Format Examples

^{pr2}$

相关问题 更多 >