将字符串转换为f-string

Fra*_* M. 9 python string-interpolation python-3.6

如何将经典string转换为f-string?:

variable = 42
user_input = "The answer is {variable}"
print(user_input)
Run Code Online (Sandbox Code Playgroud)

答案是{变量}

f_user_input = # Here the operation to go from a string to an f-string
print(f_user_input)
Run Code Online (Sandbox Code Playgroud)

答案是42

Mar*_*ers 16

f-string是语法,而不是对象类型.您无法将任意字符串转换为该语法,语法会创建一个字符串对象,而不是相反.

我假设你想user_input用作模板,所以只需在对象上使用该str.format()方法user_input:

variable = 42
user_input = "The answer is {variable}"
formatted = user_input.format(variable=variable)
Run Code Online (Sandbox Code Playgroud)

如果您想提供一个可配置模板的服务,创建具有可插值所有字段命名空间的字典,并使用str.format()**kwargs调用语法应用命名空间:

namespace = {'foo': 42, 'bar': 'spam, spam, spam, ham and eggs'}
formatted = user_input.format(**namespace)
Run Code Online (Sandbox Code Playgroud)

然后,用户可以在{...}字段中使用命名空间中的任何键(或者不使用,忽略未使用的字段).


Von*_*Von 11

真正的答案可能是:不要这样做。通过将用户输入视为 f 字符串,您将其视为会产生安全风险的代码。您必须非常确定您可以信任输入的来源。

如果您知道可以信任用户输入的情况,则可以使用eval()执行此操作:

variable = 42
user_input="The answer is {variable}"
eval("f'{}'".format(user_input))
'The answer is 42'
Run Code Online (Sandbox Code Playgroud)

编辑添加:@wjandrea 指出了另一个对此进行扩展的答案

  • @Von +1 答案,因为它还允许处理内部表达式,例如“答案是 {variable+1}”,这会引发“KeyError”,并在普通字符串(非 f 字符串)上调用“format”方法。然而,这个解决方案并不是 100% 可靠,因为它假设字符串不包含简单的引号,例如 `user_input="The 'answer' is {variable}"` 会引发一个 `SyntaxError`。这是解决此类问题的方法:`eval(f"f{repr(user_input)}")` (3认同)
  • 这是在安全方面进行扩展的[答案](/sf/answers/3331947811/) (2认同)

Kos*_*vid 7

只是添加一种类似的方法来执行相同的操作。但str.format()选项更适合使用。

variable = 42
user_input = "The answer is {variable}"
print(eval(f"f'{user_input}'"))
Run Code Online (Sandbox Code Playgroud)

一种更安全的方法可以实现与上面提到的 Martijn Pieters 相同的效果:

def dynamic_string(my_str, **kwargs):
    return my_str.format(**kwargs)

variable = 42
user_input = "The answer is {variable}"
print('1: ', dynamic_string(my_str=user_input, variable=variable))
print('2: ', dynamic_string(user_input, variable=42))
Run Code Online (Sandbox Code Playgroud)
1:  The answer is 42
2:  The answer is 42
Run Code Online (Sandbox Code Playgroud)


小智 5

variable = 42
user_input = "The answer is {variable}"
# in order to get The answer is 42, we can follow this method
print (user_input.format(variable=variable))
Run Code Online (Sandbox Code Playgroud)

(或者)

user_input_formatted = user_input.format(variable=variable)
print (user_input_formatted)
Run Code Online (Sandbox Code Playgroud)

好链接https://cito.github.io/blog/f-strings/