Search code examples
pythonstring-formatting

Formatting string which is in double curly braces


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?


Solution

  • 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"}]'