Reputation: 309
I've got following short code I need to execute
isin = 'US0028241000'
payload = f'[{"idType":"ID_ISIN", "idValue": "{isin}"}]'
It outputs a ValueError: Invalid format specifier
I also tried :
payload = '[{"idType":"ID_ISIN", "idValue": "{}"}]'.format(isin)
This one does not work as well. My thought is that it's because the curly braces located within a dict. How can I execute this piece?
Upvotes: 1
Views: 2678
Reputation: 1531
f
string consider whatever inside of the curly braces {}
is a python expression.
The problem here also is the same, you are trying to put curly braces as a dictionary but f
string considers it as an expression. When it tries to interpret we are getting ValueError: Invalid format specifier
.
Example 1:
Trying to put list
variable inside f
string
l = [1,2,3]
`f'{l}'`
Example 2:
Trying to put dict
inside f
string
You should use double curly braces.
`f'[{{"idType":"ID_ISIN", "idValue": "{isin}"}}]'`
But if you declared dict
in some variable then you probably will be using as below:
out = {"idType":"ID_ISIN", "idValue": f"{isin}"}
f'{out}'
Upvotes: 1
Reputation: 743
isin = 'US0028241000'
payload = f'[{{"idType":"ID_ISIN", "idValue": "{isin}"}}]'
print(payload)
for ignoring any curly braces while formating the string just wrap it with a {}
Upvotes: 1
Reputation: 664
The problem is the curly braces.
To escape them, try:
payload = f'[{{"idType":"ID_ISIN", "idValue": "{isin}"}}]'
Upvotes: 1
Reputation: 532093
Your title alludes to the solution. Inside an f-string, you need to use {{
and }}
for literal curly braces, but you never introduce them.
>>> f'[{{"idType":"ID_ISIN", "idValue": "{isin}"}}]'
'[{"idType":"ID_ISIN", "idValue": "US0028241000"}]'
That said, don't construct JSON values using string formatting tools; use the json
module.
>>> import json
>>> json.dumps([{'idType': 'ID_ISIN', 'idValue': isin}])
'[{"idType": "ID_ISIN", "idValue": "US0028241000"}]'
Upvotes: 3