Replace word in string using f-string

Viewed 764

In Python, I'm trying to insert a variable into an imported string that already contains the variable name - as pythonically as possible.

Import:

x = "this is {replace}`s mess" 

Goal:

y = add_name("Ben", x) 

Is there a way to use f-string and lambda to accomplish this? Or do I need to write a function?

1 Answers

Better option to achieve this will be using str.format as:

>>> x = "this is {replace}`s mess"
>>> x.format(replace="Ben")
'this is Ben`s mess'

However if it is must for you to use f-string, then:

  1. Declare "Ben" to variable named replace, and
  2. Declare x with f-string syntax

Note: Step 1 must be before Step 2 in order to make it work. For example:

>>> replace = "Ben" 
>>> x = f"this is {replace}`s mess"
      # ^ for making it f-string

>>> x
'this is Ben`s mess'   # {replace} is replaced with "Ben"
Related