2

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?

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Starscream
  • 23
  • 9
  • 1
    https://stackoverflow.com/questions/42497625/how-to-postpone-defer-the-evaluation-of-f-strings and https://stackoverflow.com/questions/54351740/how-can-i-use-f-string-with-a-variable-not-with-a-string-literal – Cory Kramer Jan 04 '21 at 14:44
  • You can do it without f-strings: `x.format(replace="Ben")` – 001 Jan 04 '21 at 14:46

1 Answers1

2

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"
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126