Question: How do I transform a classic string to an f-string?

```
variable = 42
user_input = "The answer is {variable}"
print(user_input)

```

Output: `The answer is {variable}`

```
f_user_input = # Here the operation to go from a string to an f-string
print(f_user_input)

```

Desired output: `The answer is 42`

Answer: 
An f-string is **syntax**, not an object type. You can't convert an arbitrary string to that syntax, the syntax creates a string object, not the other way around.

I'm assuming you want to use `user_input` as a template, so just use the [`str.format()` method](https://docs.python.org/3/library/stdtypes.html#str.format) on the `user_input` object:

```
variable = 42
user_input = "The answer is {variable}"
formatted = user_input.format(variable=variable)

```

If you wanted to provide a configurable templating service, create a namespace dictionary with all fields that can be interpolated, and use `str.format()` with the `**kwargs` call syntax to apply the namespace:

```
namespace = {'foo': 42, 'bar': 'spam, spam, spam, ham and eggs'}
formatted = user_input.format(**namespace)

```

The user can then use any of the keys in the namespace in `{...}` fields (or none, unused fields are ignored).
The real answer is probably: don't do this. By treating user input as an f-string, you are treating it like code which creates a security risk. You have to be really certain you can trust the source of the input.

If you are in situation where you know the user input can be trusted, you can do this with [eval()](https://docs.python.org/3/library/functions.html#eval):

```
variable = 42
user_input="The answer is {variable}"
eval("f'{}'".format(user_input))
'The answer is 42'

```

Edited to add: @wjandrea pointed out [another answer](https://stackoverflow.com/questions/47339121/how-do-i-convert-a-string-into-an-f-string/47599254#47599254) which expands on this.