我有一个包含许多替换字段的长字符串,然后我将其格式化:
firstRep = replacementDict['firstRep']
secondRep = replacementDict['secondRep']
.
.
.
nthRep = replacementDict['nthRep']
newString = oldString.format(firstRep = firstRep,
secondRep = secondRep,...,
nthRep = nthRep)
有没有办法避免必须单独设置每个选项并使用循环方法?
感谢。
答案 0 :(得分:4)
你可以unpack argument dicts with a **
prefix:
newString = oldString.format(**replacementDict)
答案 1 :(得分:3)
使用为此用例提供完全的str.format_map
:
old_string.format_map(replacement_dict)
注意:format_map
仅在python3.2 +中提供。在python2中,您可以使用**
解包(请参阅this相关问题), howerver 这会强制python复制字典,因此速度稍慢并且使用更多内存。
答案 2 :(得分:2)
你可以像这样解压缩字典
replacementDict = {}
replacementDict["firstRep"] = "1st, "
replacementDict["secondRep"] = "2nd, "
replacementDict["thirdRep"] = "3rd, "
print "{firstRep}{secondRep}{thirdRep}".format(**replacementDict)
# 1st, 2nd, 3rd,
Accessing arguments by name:
>>>
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'