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.

3

2 Answers 2

4

You need:

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

val1 = 1
val2 = 77

print(eval(f"f'{str1}'"))
1
  • 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. Commented Nov 19, 2019 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.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.