How to generate string dynamically in Python (Observer Pattern)

Viewed 2986

Supposing we have the code below:

var1="top"
var2=var1+"bottom"

We want to change var1 value if a condition is true:

if COND==True:
  var1="changed"

Now I want to have var2 dynamically changed. With the code above, var2 will still have the value "topbottom".

How can I do that?

Thanks

4 Answers

As others have said, since strings are immutable you must find a way to insert the dynamic value on the formation of the string.

I am a fan of the new 'fstrings' in Python- single line 'if' statement for flare:

cond = True

var1 = "changed" if cond is True else "top"
var2 = f"{var1} bottom"

print(var2)
Related