Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving a variable dynamically in python [closed]

Say I have a string -

my_str = "From {country} with Love"

Variable country is not available at the moment and is set at a later stage to

country = "Russia".

Now Can I print string with the inline variable value dynamically resolved. Something like -

print(f"{my_str}")

which will output

From Russia with Love

I tried to use eval() but didn't help.

like image 934
VK. Avatar asked Sep 15 '26 09:09

VK.


1 Answers

my_str = "From {} with Love"
country = "Russia"
print(my_str.format(country))

If you like to work with names you can also do:

my_str = "From {country} with Love"
country = "Russia"
print(my_str.format(country=country))
like image 153
Andreas Avatar answered Sep 16 '26 23:09

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!