我如何将f字符串与变量一起使用,而不是与字符串文字一起使用? [英] How can i use f-string with a variable, not with a string literal?
问题描述
我想将f-string与我的字符串变量一起使用,而不要与由字符串文字"..."
定义的字符串一起使用.
I want to use f-string with my string variable, not with string defined with a string literal, "..."
.
这是我的代码
name=["deep","mahesh","nirbhay"]
user_input = r"certi_{element}" # this string i ask from user
for element in name:
print(f"{user_input}")
此代码提供输出:
certi_{element}
certi_{element}
certi_{element}
但是我想要
certi_{deep}
certi_{mahesh}
certi_{nirbhay}
我该怎么做?
推荐答案
f"..."
字符串非常有用,但是您没有文字,却有一个模板字符串放在单独的变量中.
f"..."
strings are great when interpolating expression results into a literal, but you don't have a literal, you have a template string in a separate variable.
您可以使用 str.format()
将值应用于该模板:
You can use str.format()
to apply values to that template:
name=["deep","mahesh","nirbhay"]
user_input = "certi_{element}" # this string i ask from user
for value in name:
print(user_input.format(element=value))
使用名称(例如{element}
)的字符串格式占位符不是变量.您可以在str.format()
调用的关键字参数中为每个名称分配一个值.在上面的示例中,element=value
传入value
变量的值,以使用element
填充占位符.
String formatting placeholders that use names (such as {element}
) are not variables. You assign a value for each name in the keyword arguments of the str.format()
call instead. In the above example, element=value
passes in the value of the value
variable to fill in the placeholder with the element
.
与f
-字符串不同,{...}
占位符不是不是表达式,并且您不能在模板中使用任意Python表达式.这是一件好事,您不希望最终用户能够在您的程序中执行任意Python代码.有关详细信息,请参见 格式字符串语法文件 .
Unlike f
-strings, the {...}
placeholders are not expressions and you can't use arbitrary Python expressions in the template. This is a good thing, you wouldn't want end-users to be able to execute arbitrary Python code in your program. See the Format String Syntax documenation for details.
您可以输入任意数量的名称;字符串模板没有可以使用它们中的任何一个.如果将str.format()
与**mapping
调用约定结合使用,则可以使用任何词典作为值的来源:
You can pass in any number of names; the string template doesn't have to use any of them. If you combine str.format()
with the **mapping
call convention, you can use any dictionary as the source of values:
template_values = {
'name': 'Ford Prefect',
'number': 42,
'company': 'Sirius Cybernetics Corporation',
'element': 'Improbability Drive',
}
print(user_input.format(**template_values)
以上内容使用户可以随意使用模板中template_values
中的任何名称.
The above would let a user use any of the names in template_values
in their template, any number of times they like.
虽然您可以使用locals()
和globals()
来生成将变量名映射到值的字典,但我不建议您使用这种方法.使用上述专用的名称空间来限制可用的名称,并为最终用户记录这些名称.
While you can use locals()
and globals()
to produce dictionaries mapping variable names to values, I'd not recommend that approach. Use a dedicated namespace like the above to limit what names are available, and document those names for your end-users.
这篇关于我如何将f字符串与变量一起使用,而不是与字符串文字一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!