我有一个长字符串,其中包含许多替换字段,然后我使用这些字段格式化:

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

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

有没有办法避免必须单独设置每个选项并使用循环方法来实现这一点?
谢谢。

最佳答案

你可以这样把字典拆开

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

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

引用Format Examples
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'

关于python - 使用.format()和很多替换字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22129803/

10-12 20:54