使用 f-string 替换字符串中的单词

Replace word in string using f-string

在 Python 中,我尝试将变量插入到已包含变量名称的导入字符串中 - 尽可能采用 Python 方式。

导入:

x = "this is {replace}`s mess" 

目标:

y = add_name("Ben", x) 

有没有办法使用 f-string 和 lambda 来完成这个?或者我需要写一个函数吗?

实现此目的的更好选择是使用 str.format 作为:

>>> x = "this is {replace}`s mess"
>>> x.format(replace="Ben")
'this is Ben`s mess'

但是,如果您必须使用 f-string,则:

  1. 向名为 replace 的变量声明 "Ben",并且
  2. 使用 f 字符串语法声明 x

注意:第 1 步必须在第 2 步之前才能生效。例如:

>>> replace = "Ben" 
>>> x = f"this is {replace}`s mess"
      # ^ for making it f-string

>>> x
'this is Ben`s mess'   # {replace} is replaced with "Ben"