0

I have a string that contains an arbitrary number of inserts in the form of variables names that will be in the global namespace. Please note the future tense - the variables do not yet exist at the moment when the formatted string is created.

txt = "{x} --- {y}" # could very well be "{z} --- {x} --- {w}"
x = "A"
y = "B"

When the string needs to be evaluated (and all variables exist), I need to specify each of the inserts by name. However, since it doesn't use the same variables each time, the only way is to parse the string and extract the variable names

BogdanC
  • 1,316
  • 3
  • 16
  • 36
  • 2
    `txt.format(**globals())` – kindall Oct 19 '22 at 13:46
  • Could you be more specific about the context you need to format the string? Something more representative of your code rather than x, y, z and w being given arbitrary values. For example, does it need to be reused in multiple places? What do you want to use the formatted text for? – Jasmijn Oct 19 '22 at 13:56
  • 1
    `' --- '.join(items)` with `items = [x, y, z, ...]`. – Richard Neumann Oct 19 '22 at 13:58

1 Answers1

1

Two options that come to mind:

  1. Brute force f-string conversion, because every body loves eval:
txt = eval(f"f'{txt}'")

or, a little more cryptic, and as kindall proposed:

  1. format the complete available global namespace into your text by unpacking globals() into your string's format method.
txt.format(**globals())
Christian Karcher
  • 2,533
  • 1
  • 12
  • 17