3

Is there a way to dynamically change/substitute one of f-string variables? Let's say I have format as follows:

expected = f'{var} {self.some_evaluation_1(var)} {self.some_evaluation_2(var)}'

Then I have test case with multiple assertions:

var1='some value 1'
var2='some value 2'
var3='some value 3'

var=var1
self.assertEqual('some great value1', expected)
var=var2
self.assertEqual('some great value2', expected)
var=var3
self.assertEqual('some great value3', expected)

Is there a way to make f-string use my variable instead of defined in initial format?

# Let's say something like this? It's just a concept I know it doesn't work.
self.assertEqual('some great value1', expected % var1)

2 Answers 2

9

No, the result of an f-string expression is an immutable string. Similar to:

y = 'abc'
x = y + 'def' # result of expression is immutable string.
y = 'ghi'
print(x)  # would you expect 'ghidef'? No...

If you want it to change, use format instead of f-strings to re-evaluate expected:

expected = 'test{}' # NOT an f-string
var = 1
assert expected.format(var) == 'test1'
var = 2
assert expected.format(var) == 'test2'

If you have named variables as in your example, you can use:

expected = 'test{var}'
assert expected.format(var=1) == 'test1'

or pass locals() as a dictionary of arguments using keyword expansion (**):

expected = 'test{a}{b}'
a = 1
b = 2
assert expected.format(**locals()) == 'test12'
Sign up to request clarification or add additional context in comments.

Comments

-2

Try using eval:

myf = "f\"" + whathever + "\""

eval(myf)

3 Comments

eval is evil. What's wrong with accepted answer?
OP's question implies they want to define expected once, then change its value depending on the (delayed) evaluation of var. There's no need to dynamically evaluate a f-string literal to accomplish this.
@chepner my answer focus only on solving how to "creatie f string dinamicaly" Just this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.