-1

I'm trying to pull a string from JSON, then convert it to an f string to be used dynamically. Example Assigned from JSON I get

whose_fault= "{name} started this whole mess"

How to build a lambda to convert it to an f-string and insert the given variable? I just can't quite get my head around it. I know similar questions have been asked, but no answer seems to quite work for this.

Better question. What's the most pythonic way to insert a variable into a string (which cannot be initially created as an f-string)? My goal would be a lambda function if possible. The point being to insert the same variable into whatever string is given where indicated said string.

Starscream
  • 23
  • 9
  • f-strings allow arbitrary code execution. Someone can make an f-string install ransomware or email your customers' private data to Nigeria. This is a bad idea - use something else. – user2357112 Jan 02 '21 at 15:49
  • I don't do Python, but as far as I can tell, an [f-string](https://www.python.org/dev/peps/pep-0498/) is a string **literal** that supports interpolation as part of the literal syntax. As such, it's a source code construct. You can't create one dynamically at runtime (if I'm reading correctly) (unless Python has a means of allowing you to execute code in a string, which would be problematic from a security standpoint). – T.J. Crowder Jan 02 '21 at 15:50
  • 1
    There is no such thing as f-string in python. Its just a feature to allow you execute a code instead of using concatination. So if you have a variable `x= 1011`, then you can create another string that contains the variable x in it. Like `y = f"its now {x*2}"`, now `y` is a string. not a function or a type – Aven Desta Jan 02 '21 at 15:52

1 Answers1

0

There is no such thing as f-string type object in python. Its just a feature to allow you execute a code and format a string. So if you have a variable x= 2020, then you can create another string that contains the variable x in it. Like

y = f"It is now {x+1}". Now y is a string, not a new object type,not a function

Aven Desta
  • 2,114
  • 12
  • 27