Transform string to f-string

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 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).

Leave a Comment