0

Let's suppose I get some string and set it to variable - it can't be created as f-string:

str1 = 'date time for {val1} and {val2}'

Then variables inside the string initialized:

val1 = 1
val2 = 77

Calling print(str1) will return 'date time for {val1} and {val2}'. But I would like to get 'date time for 1 and 77'

Is there any function to make a string as a F string? So I want to call something make_F(str1) and get f-string

PS I cant use dict {'val1':1, 'val2':77} with .format because don't know which variables will be needed in the string. I just want magic happen with F-string.

Rocketq
  • 5,423
  • 23
  • 75
  • 126

2 Answers2

4

You need:

str1 = 'date time for {val1} and {val2}'

val1 = 1
val2 = 77

print(eval(f"f'{str1}'"))
Mario Camilleri
  • 1,457
  • 11
  • 24
  • Two warnings if you're using this. Firstly, make sure str1 comes from a trusted source, since eval will execute any Python commands contained in it. Secondly, str1 should not be a multi-line string - if it is, then use eval(f'f"""{str1}"""') otherwise eval will throw an EOL error. – Mario Camilleri Nov 19 '19 at 16:25
1

You first need to describe variables as e.g

var1 = None
var2 = None

Then you can use it with f-string like this:

x = f'print {var1} and {var2}'

print(x)

And thats it, you will get the result.

simkusr
  • 770
  • 2
  • 11
  • 20