从普通字符串构建F字符串 [英] Build f-strings from normal strings

查看:107
本文介绍了从普通字符串构建F字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试新的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}'")

解决方案

有可能吗?

否,除了以类似方式进行evalexec 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 evaling or execing 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆