0

Suppose I have this example

word1 = "filled"
word2 = "verbs"
word3 = "nouns"
test_string1 = f"I {word1} in these {word2} and {word3}."

If you print this, you get

I filled in these verbs and nouns.

Now, suppose Instead I first do this

test_string2 = "I {word1} in these {word2} and {word3}."

Is there a way to fill in this second string with the corresponding variables?

I tried

test_string3 = f test_string2

But that didn't work.

  File "<ipython-input-25-d1b8ffc3fdb5>", line 1
    test_string3 = f test_string2
                                ^
SyntaxError: invalid syntax
Stan Shunpike
  • 2,165
  • 3
  • 20
  • 32
  • 3
    Does this answer your question? [Is it possible to reuse an f-string as it is possible with a string and format?](https://stackoverflow.com/questions/52248776/is-it-possible-to-reuse-an-f-string-as-it-is-possible-with-a-string-and-format) – Julia Feb 15 '22 at 15:29
  • 3
    `f` isn't a function. For what you want to do, you can use `.format()` str method. – C14L Feb 15 '22 at 15:29

2 Answers2

3

You can't. Closest you can get is:

word1 = "filled"
word2 = "verbs"
word3 = "nouns"
test_string1 = "I {word1} in these {word2} and {word3}.".format(**locals())
bvan
  • 169
  • 4
2

Use test_string2.format(word1=word1, word2=word2, word3=word3).

timgeb
  • 76,762
  • 20
  • 123
  • 145