Python fstring 作为函数

标签 python string f-string

与 string.Template() 或其他方法相比,我喜欢使用 Python f-string,因为它的语法简单。然而,在我的应用程序中,字符串是从文件中加载的,变量的值只能稍后提供。

是否有办法调用与字符串定义分开的 fstring 功能?希望下面的代码能更好地解释我希望实现的目标。

a = 5
s1 = f'a is {a}' # prints 'a is 5'

a = 5
s2 = 'a is {a}'
func(s2) # what should be func equivalent to fstring

最佳答案

通过使用 eval() 并将 locals() 或任何任意字典作为第二个位置 locals 参数,您可以计算一个使用任意输入组合动态地动态 f 字符串。

def fstr(fstring_text, locals, globals=None):
    """
    Dynamically evaluate the provided fstring_text
    """
    locals = locals or {}
    globals = globals or {}
    ret_val = eval(f'f"{fstring_text}"', locals, globals)
    return ret_val

示例用法:

format_str = "{i}*{i}={i*i}"
i = 2
fstr(format_str, locals()) # "2*2=4"
i = 4
fstr(format_str, locals()) # "4*4=16"
fstr(format_str, {"i": 12}) # "10*10=100"

关于Python fstring 作为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47597831/

相关文章:

python - CryptoJS HmacSHA256 加密结果与Python不同

c++ - 字符串引用和 const char 指针的函数重载

python - 使用文字字符串插值或f字符串时出现SyntaxError

python - 防止 f 字符串将 float 转换为科学记数法

python - ' ' 对象不可迭代。 Django 1.11

python - pytest/unittest : mock. 来自模块的补丁功能?

python - Golang 相当于使用 F 字符串的 Python 格式化字符串

Java String split 删除了空值

string - 了解 DC3/Skew 算法的实现以创建后缀数组线性时间

python - 帮我用 f-string 修复这个代码吗?