Transform string to f-string

一世执手 提交于 2019-12-06 22:41:50

问题


How do I transform a classic string to an f-string ? :

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

The answer is {variable}

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

The answer is 42


回答1:


An f-string is syntax, not an object type. 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:

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:

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




回答2:


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://stackoverflow.com/questions/44757222/transform-string-to-f-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!