1

I want to use my dictionary parameter in my string Here is my dictionary

a = {"first_name": "ABC", "last_name": "PQR"}

Following statement gives correct output

"{first_name}{last_name}".format(**a)

But I want following output

"{ Hello {first_name} {last_name}.}".format(**a)
>>> '{ Hello ABC PQR.}'

It gives keyerror

KeyError                                  Traceback (most recent call last)
<ipython-input-50-84fc42fb81f2> in <module>()
----> 1 "{ Hello {first_name} {last_name}.}".format(**a)

KeyError: ' Hello {first_name} {last_name}'
Cœur
  • 37,241
  • 25
  • 195
  • 267
NIKHIL RANE
  • 4,012
  • 2
  • 22
  • 45

3 Answers3

2

You don't need to include Hello in the formatting:

"{{Hello {first_name} {last_name}.}}".format(**a)

# "{Hello ABC PQR.}"

Use double curly braces {{}} to escape {}

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

I think what you mean is

"{{ Hello {first_name} {last_name}.}}".format(**a)
phogl
  • 494
  • 1
  • 8
  • 16
0

You can enter literal braces by doubling them:

>>> a = {"first_name": "ABC", "last_name": "PQR"}
>>> "{{ Hello {first_name} {last_name}.}}".format(**a)
'{ Hello ABC PQR.}'
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97