François M.
François M.

Reputation: 4278

Transform string to f-string

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

Upvotes: 45

Views: 32044

Answers (5)

Kostia Medvid
Kostia Medvid

Reputation: 1299

Just to add one more similar way how to do the same. But str.format() option is much preferable to use.

variable = 42
user_input = "The answer is {variable}"
print(eval(f"f'{user_input}'"))

A safer way to achieve the same as Martijn Pieters mentioned above:

def dynamic_string(my_str, **kwargs):
    return my_str.format(**kwargs)

variable = 42
user_input = "The answer is {variable}"
print('1: ', dynamic_string(my_str=user_input, variable=variable))
print('2: ', dynamic_string(user_input, variable=42))
1:  The answer is 42
2:  The answer is 42

Upvotes: 7

Unmesh Rajadhyaksha
Unmesh Rajadhyaksha

Reputation: 1

You can use f-string instead of normal string.

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

Upvotes: -8

Von
Von

Reputation: 4525

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():

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 which expands on this.

Upvotes: 21

priya raj
priya raj

Reputation: 362

variable = 42
user_input = "The answer is {variable}"
# in order to get The answer is 42, we can follow this method
print (user_input.format(variable=variable))

(or)

user_input_formatted = user_input.format(variable=variable)
print (user_input_formatted)

Good link https://cito.github.io/blog/f-strings/

Upvotes: 6

Martijn Pieters
Martijn Pieters

Reputation: 1124070

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

Upvotes: 80

Related Questions