从普通字符串构建F字符串 [英] Build f-strings from normal strings
问题描述
我正在尝试新的f字符串,我想知道是否有可能将普通字符串编译"为f字符串. 因此,可以控制f字符串的评估时间,并能够在使用它们之前定义f字符串.
示例伪代码:
a = 'normal string with some curly {inside}'
inside = 'in it!'
print(a.make_f_string())
>>> 'normal string with some curly in it!'
所以基本上我需要在它包含的变量之前定义f字符串.或将字符串设置为f字符串.
我尝试使用它们的嵌套功能(SO),但是没有运气./p>
有可能吗?到目前为止,我发现的唯一方法是使用eval(),而且似乎不是实现它的好方法.
eval(f"f'{a}'")
有可能吗?
否,除了以类似方式进行eval
或exec
ing外,您不能执行此操作.
由于要在需要实际格式化之前尝试定义格式,因此需要.format
而不是f
字符串.
I'm trying the new f-strings, and I'm wondering if it's possible to "compile" a normal string into an f-string. So to have control on the evaluation time of the f-string, and be capable of defining f-strings before consuming them.
Example pseudo-code:
a = 'normal string with some curly {inside}'
inside = 'in it!'
print(a.make_f_string())
>>> 'normal string with some curly in it!'
So basically my need is to define the f-string before the variable that it contains. or make a string an f-string.
I tried to play with the nesting capabilities of them (SO) but with no luck.
Is it possible? So far the only way I found is with eval(), and seems far from a good way to do it.
eval(f"f'{a}'")
Is it possible?
No, apart from eval
ing or exec
ing in a similar fashion, you can't do this.
Since you are trying to define a format before actual formatting is needed, you need .format
, not f
-strings.
这篇关于从普通字符串构建F字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!