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?

2

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.