如何将经典字符串转换为f-字符串?
variable = 42
user_input = "The answer is {variable}"
print(user_input)
输出:答案是 {variable}
f_user_input = # Here the operation to go from a string to an f-string
print(f_user_input)
期望输出:答案是42
如何将经典字符串转换为f-字符串?
variable = 42
user_input = "The answer is {variable}"
print(user_input)
输出:答案是 {variable}
f_user_input = # Here the operation to go from a string to an f-string
print(f_user_input)
期望输出:答案是42
f-string是一种语法,而不是对象类型。您无法将任意字符串转换为该语法,该语法创建字符串对象,而不是相反。
我假设您想使用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+1}"
,这会引发在普通字符串(非 f-strings)上调用 format
方法时出现的 KeyError
。然而,这种解决方案并不百分之百可靠,因为它假设字符串不包含简单引号,例如
user_input="The 'answer' is {variable}"
会引发 SyntaxError
。以下是解决此问题的方法:
eval(f"f{repr(user_input)}")
- Pierre Denisvariable = 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)
Good link https://cito.github.io/blog/f-strings/
只是为了补充一种类似的做法。 但是使用 str.format() 选项更加推荐。
variable = 42
user_input = "The answer is {variable}"
print(eval(f"f'{user_input}'"))
实现与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))
1: The answer is 42
2: The answer is 42
variable = 42
user_input = f"The answer is {variable}"
print(user_input)
formatted = user_input.format(**locals())
- Arjun Ariyillocals()
比其他建议使用eval
的答案更好。 - Arjun Ariyila = {'b': 'hi'}
,你不能这样做"test {a['b']}".format(a=a)
,而应该这样做"test {a[b]}".format(a=a)
。 - undefined