小能豆

How do I convert a string into an f-string?

py

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:

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:

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'

阅读 87

收藏
2023-12-12

共1个答案

小能豆

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.

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:

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.

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.

2023-12-12