2

I have a long string with many replacement fields that I then format with:

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

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

Is there a way to avoid having to set every option individually and use a looped approach to this?

Thanks.

elelias
  • 4,552
  • 5
  • 30
  • 45

3 Answers3

4

You can unpack argument dicts with a ** prefix:

newString = oldString.format(**replacementDict)
Ry-
  • 218,210
  • 55
  • 464
  • 476
3

Use str.format_map which is provided exactly for this usecase:

old_string.format_map(replacement_dict)

Note: format_map is provided only in python3.2+. In python2 you can use ** unpacking (see this related question), howerver this forces python to copy the dictionary and is thus a bit slower and uses more memory.

Community
  • 1
  • 1
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
2

You can simply unpack the dictionary like this

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

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

Quoting from the 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'
thefourtheye
  • 233,700
  • 52
  • 457
  • 497