如何将字符串转换为f字符串? [英] How do I convert a string into an f-string?

查看:185
本文介绍了如何将字符串转换为f字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关Python的新内容的 博客 f弦,它们看起来真的很整齐.但是,我希望能够从字符串或文件中加载f字符串.

I was reading this blog on python's new f-strings and they seem really neat. However, I want to be able to load an f-string from a string or file.

我似乎找不到任何执行此操作的字符串方法或其他函数.

I can't seem to find any string method or other function that does this.

来自上面链接中的示例:

From the example in my link above:

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'

但是如果我有一个字符串s怎么办?我希望能够修饰s,如下所示:

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)


结果证明,我已经可以执行与str.format类似的操作,并获得更高的性能.即:


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'

推荐答案

f字符串是代码.不仅以安全的方式(当然,字符串文字就是代码),而且以危险的任意代码执行方式.这是有效的f字符串:

f-strings are code. Not just in the safe, "of course a string literal is code" way, but in the dangerous, arbitrary-code-execution way. This is a valid f-string:

f"{__import__('os').system('install ransomware or something')}"

,它将在评估后执行任意的shell命令.

and it will execute arbitrary shell commands when evaluated.

您在问如何获取从文本文件加载的字符串并将其作为代码进行评估,答案归结为eval.当然,这是安全风险,并且可能是个坏主意,因此,我建议不要尝试从文件中加载f字符串.

You're asking how to take a string loaded from a text file and evaluate it as code, and the answer boils down to eval. This is of course a security risk and probably a bad idea, so I recommend not trying to load f-strings from files.

如果要从文件加载f字符串f"My name is {name} and I am {age} years old",请实际放置

If you want to load the f-string f"My name is {name} and I am {age} years old" from a file, then actually put

f"My name is {name} and I am {age} years old"

文件中的

f和引号以及所有内容.

in the file, f and quotation marks and all.

从文件中读取,编译并保存(因此eval不必每次都重新编译):

Read it from the file, compile it and save it (so eval doesn't have to recompile it every time):

compiled_fstring = compile(fstring_from_file, '<fstring_from_file>', 'eval')

并使用eval进行评估:

formatted_output = eval(compiled_fstring)

如果这样做,请非常注意从中加载f字符串的来源.

If you do this, be very careful about the sources you load your f-strings from.

这篇关于如何将字符串转换为f字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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