1

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.

VK.
  • 421
  • 5
  • 11

6 Answers6

6
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))
Andreas
  • 8,694
  • 3
  • 14
  • 38
1

I would suggest using Templating for example Pythons built in templating:

from string import Template

t = Template("From $country with Love")
s = t.substitute(country="Russia")
print(s)
jasLogic
  • 11
  • 1
  • 3
0

You can create the variable like this:

my_str = f"From {country} with Love"

Then when the country variable gets assigned it will be replaced automatically in the my_str variable.

pacuna
  • 1,831
  • 16
  • 15
  • 3
    Note that this will raise an NameError when you try to print the string without initiating the variable `country`. – JarroVGIT Aug 06 '20 at 18:29
  • Correct @DjerroNeth, I get the error ```NameError: name 'country' is not defined```. @pacuna I don't have the variable set while assigning my_str. It becomes available at a later stage. – VK. Aug 06 '20 at 18:35
0

This should work

variable = "Russia"
print(f'my country is {variable} and I live in it')
0

This should work too:

country = "Russia"
my_str = f"From {country} with Love"
print(f"{my_str}")
  • For f-string you have to initialize "country" before the string. also you then could simply do: print(my_str) – Andreas Aug 06 '20 at 18:33
  • Thanks, good point. Btw, can f-strings be used for a variable definition like in the example I've posted above? – Eugene Anufriev Aug 06 '20 at 18:44
  • I don't think so because as far as I am aware f strings are syntax not objects. And are most likely not be able to manipulate sytax through a string. – Andreas Aug 06 '20 at 18:47
  • heh, I think I found the answer here: https://stackoverflow.com/questions/41306928/why-dont-f-strings-change-when-variables-they-reference-change – Eugene Anufriev Aug 06 '20 at 18:52
  • ah, good explaination, far better then I could do :P – Andreas Aug 06 '20 at 18:55
0

Here's an idea:

def str(country):
  my_str="From %s with Love" %country
  print(my_str)
str("Russia")

This will print From Russia with Love.