简体   繁体   English

将字符串转换为 f 字符串

[英]Transform string to f-string

How do I transform a classic string to an f-string?如何将经典字符串转换为 f 字符串?

variable = 42
user_input = "The answer is {variable}"
print(user_input)

Output: The answer is {variable}输出: The answer is {variable}

f_user_input = # Here the operation to go from a string to an f-string
print(f_user_input)

Desired output: The answer is 42期望输出: The answer is 42

An f-string is syntax , not an object type. f 字符串是语法,而不是对象类型。 You can't convert an arbitrary string to that syntax, the syntax creates a string object, not the other way around.您不能将任意字符串转换为该语法,该语法会创建一个字符串对象,而不是相反。

I'm assuming you want to use user_input as a template, so just use the str.format() method on the user_input object:我假设您想使用user_input作为模板,因此只需在user_input对象上使用str.format()方法

variable = 42
user_input = "The answer is {variable}"
formatted = user_input.format(variable=variable)

If you wanted to provide a configurable templating service, create a namespace dictionary with all fields that can be interpolated, and use str.format() with the **kwargs call syntax to apply the namespace:如果您想提供可配置的模板服务,请创建一个包含所有可以插入的字段的命名空间字典,并使用带有**kwargs调用语法的str.format()来应用命名空间:

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

The user can then use any of the keys in the namespace in {...} fields (or none, unused fields are ignored).然后,用户可以在{...}字段中使用命名空间中的任何键(或者没有,忽略未使用的字段)。

The real answer is probably: don't do this.真正的答案可能是:不要这样做。 By treating user input as an f-string, you are treating it like code which creates a security risk.通过将用户输入视为 f 字符串,您将其视为会产生安全风险的代码。 You have to be really certain you can trust the source of the input.您必须非常确定您可以信任输入的来源。

If you are in situation where you know the user input can be trusted, you can do this with eval() :如果您知道可以信任用户输入的情况,则可以使用eval()执行此操作:

variable = 42
user_input="The answer is {variable}"
eval("f'{}'".format(user_input))
'The answer is 42'

Edited to add: @wjandrea pointed out another answer which expands on this.编辑添加:@wjandrea 指出了另一个对此进行扩展的答案

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

(or) (或)

user_input_formatted = user_input.format(variable=variable)
print (user_input_formatted)

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

Just to add one more similar way how to do the same.只是添加一种类似的方法来做同样的事情。

variable = 42
user_input = "The answer is {variable}"
print(eval(f"f'{user_input}'"))

You can use f-string instead of normal string.您可以使用 f-string 代替普通字符串。

variable = 42
user_input = f"The answer is {variable}"
print(user_input) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM