python - 如何将 f-string 与变量一起使用,而不是与字符串文字一起使用?

标签 python python-3.x string string-formatting f-string

我想将 f-string 与我的字符串变量一起使用,而不是用字符串文字 "..." 定义的字符串。

这是我的代码:

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"..." 字符串在将表达式结果插入文字时非常有用,但你没有文字,你有一个模板字符串单独的变量。

您可以使用 str.format()将值应用于该模板:

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填充占位符。

f 字符串不同,{...} 占位符不是表达式,您不能在模板。这是一件好事,您不希望最终用户能够在您的程序中执行任意 Python 代码。查看Format String Syntax documenation了解详情。

你可以传入任意数量的名字;字符串模板没有使用它们中的任何一个。如果将 str.format()**mapping 调用约定结合使用,则可以使用任何字典作为值的来源:

template_values = {
    'name': 'Ford Prefect',
    'number': 42,
    'company': 'Sirius Cybernetics Corporation',
    'element': 'Improbability Drive',
}

print(user_input.format(**template_values)

以上将允许用户在他们的模板中使用 template_values 中的任何名称,任意次数。

虽然您可以使用 locals()globals() 生成将变量名映射到值的字典,但我不推荐这种方法。使用如上所述的专用命名空间来限制可用的名称,并为您的最终用户记录这些名称。

关于python - 如何将 f-string 与变量一起使用,而不是与字符串文字一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54351740/

相关文章:

python - 使用 f 字符串格式化字符串

python - 使用信号在类之间进行通信

python - 如何正确初始化神经网络模型中所需的向量?

python-3.x - Matplotlib 通过循环为 y 刻度标签着色

c++ - 使用 C++ 替换 std::string 中的子字符串但不是全部

php - 从 PHP 字符串中删除控制字符

python - 如何修复 libpapi.so.* 在运行带跟踪的 (py)COMPSs 时无法打开共享对象文件?

python - 为什么 timeit.timeit 在使用变量时会出错?

Python 和 Nameko - GreenSSLSocket 没有公共(public)构造函数。实例由 SSLContext.wrap_socket() 返回。

c++ - 如何将 std::copy 字符串复制到具有 std::string 字段的结构