簡體   English   中英

將字符串轉換為 f 字符串

[英]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)

然后,用戶可以在{...}字段中使用命名空間中的任何鍵(或者沒有,忽略未使用的字段)。

真正的答案可能是:不要這樣做。 通過將用戶輸入視為 f 字符串,您將其視為會產生安全風險的代碼。 您必須非常確定您可以信任輸入的來源。

如果您知道可以信任用戶輸入的情況,則可以使用eval()執行此操作:

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

編輯添加:@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))

(或)

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

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

只是添加一種類似的方法來做同樣的事情。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM