pythonpython-3.xf-string

Dynamically change one of f-string variables


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)

Solution

  • 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'