相关疑难解决方法(0)

如何将字符串转换为f-string

我正在阅读关于python的新f字符串的博客,它们看起来非常整洁.但是,我希望能够从字符串或文件加载f-string.

我似乎找不到任何字符串方法或其他功能.

从上面链接中的示例:

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'
Run Code Online (Sandbox Code Playgroud)

但是,如果我有一个字符串s怎么办?我希望能够有效s,这样的事情:

name = 'Fred'
age = 42
s = "My name is {name} and I am {age} years old"
effify(s)
Run Code Online (Sandbox Code Playgroud)

事实证明,我已经可以执行类似的操作str.format并获得性能提升.即:

format = lambda name, age: f"My name is {name} and I am {age} years old"
format('Ted', 12)

'My name is Ted and …
Run Code Online (Sandbox Code Playgroud)

python python-3.6 f-string

21
推荐指数
3
解决办法
6225
查看次数

Python fstring作为函数

与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)

python string f-string

5
推荐指数
2
解决办法
1198
查看次数

标签 统计

f-string ×2

python ×2

python-3.6 ×1

string ×1