[英]Transform string to f-string
如何將經典字符串轉換為 f 字符串?
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
f 字符串是語法,而不是對象類型。 您不能將任意字符串轉換為該語法,該語法會創建一個字符串對象,而不是相反。
我假設您想使用user_input
作為模板,因此只需在user_input
對象上使用str.format()
方法:
variable = 42
user_input = "The answer is {variable}"
formatted = user_input.format(variable=variable)
如果您想提供可配置的模板服務,請創建一個包含所有可以插入的字段的命名空間字典,並使用帶有**kwargs
調用語法的str.format()
來應用命名空間:
namespace = {'foo': 42, 'bar': 'spam, spam, spam, ham and eggs'}
formatted = user_input.format(**namespace)
然后,用戶可以在{...}
字段中使用命名空間中的任何鍵(或者沒有,忽略未使用的字段)。
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))
(或)
user_input_formatted = user_input.format(variable=variable)
print (user_input_formatted)
只是添加一種類似的方法來做同樣的事情。
variable = 42
user_input = "The answer is {variable}"
print(eval(f"f'{user_input}'"))
您可以使用 f-string 代替普通字符串。
variable = 42
user_input = f"The answer is {variable}"
print(user_input)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.