ida*_*ika 5 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
Run Code Online (Sandbox Code Playgroud)
通过使用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
Run Code Online (Sandbox Code Playgroud)
使用示例:
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"
Run Code Online (Sandbox Code Playgroud)
你可以这样格式化它。传入 a 的可能值的字典并将其映射到您的字符串。
dictionary = {
'a':[5,10,15]
}
def func(d):
for i in range(3):
print('a is {{a[{0}]}}'.format(i).format_map(d))
func(dictionary)
Run Code Online (Sandbox Code Playgroud)
打印:
a is 5
a is 10
a is 15
Run Code Online (Sandbox Code Playgroud)