I can’t seem to find any string method or other function that does this.
From the example in the blog post:
name = 'Fred' age = 42 f"My name is {name} and I am {age} years old" 'My name is Fred and I am 42 years old'
But what if I had a string s? I want to be able to eff-ify s, something like this:
s
name = 'Fred' age = 42 s = "My name is {name} and I am {age} years old" effify(s)
It turns out I can already perform something similar to str.format and garner the performance pick up. Namely:
str.format
format = lambda name, age: f"My name is {name} and I am {age} years old" format('Ted', 12) 'My name is Ted and I am 12 years old'
It seems like you’re looking for a way to achieve f-string-like behavior without using the f-string syntax directly, similar to the format lambda function you provided. While Python’s f-strings provide a concise and readable syntax for string formatting, you can indeed achieve similar functionality using other approaches.
format
One approach is to use the format method along with the locals() function to access local variables. This can be useful if you want to avoid using the f-string syntax directly:
locals()
name = 'Fred' age = 42 s = "My name is {name} and I am {age} years old" result = s.format(**locals()) print(result)
This will produce the desired output:
'My name is Fred and I am 42 years old'
In this example, locals() returns a dictionary containing all local variables, and **locals() unpacks this dictionary into the format method, allowing you to reference local variables in the string.
**locals()
Keep in mind that while this achieves a similar result, f-strings are generally more concise, readable, and efficient, especially in terms of performance. If you’re working with Python versions that support f-strings (Python 3.6 and later), using f-strings directly is often the recommended approach.