Python - 你能 "refresh" 一个用新的子变量重新初始化的变量吗?

Python - can you "refresh" a variable to re-initialize with new sub-variables?

假设我想声明一个字符串供我的整个 class 使用,但该字符串的一部分可能会在以后更改。是否可以只声明一次字符串,然后再“刷新”它?

示例:

substring = ""
my_long_string = f"This is a long string using another {substring} in it."
    
def printMyString(newString):
    substring = newString
    print(my_long_string)

printMyString(newString="newer, better substring")

我能否调整此代码,以便最终打印出 This is a long string using another newer, better substring in it.而无需 稍后再次声明长字符串?

我唯一的猜测是这样的:

substring = ""

def regenerate_string(substring):
    return f"This is a long string using another {substring} in it."
        
def printMyString(newString):
    print(regenerate_string(newString))

printMyString(newString="newer, better substring")

但我想问一下 Python 中是否有内置函数可以做到这一点?

不要使用 f-string,使用占位符 {} 声明模板字符串并在必要时使用 format()

my_long_string = "This is a long string using another {} in it."

print(my_long_string.format("newer, better substring")) # This is a long string using another newer, better substring in it.
print(my_long_string.format("some other substring")) # This is a long string using another some other substring in it.

您可以插入任意数量的子串

string = "With substrings, this {} and this {}."
print(string.format("first", "second")) # With substrings, this first and this second.

你也可以使用变量

string = "With substrings, this {foo} and this {bar}."
print(string.format(foo="first", bar="second")) # With substrings, this first and this second.
print(string.format(bar="first", foo="second")) # With substrings, this second and this first.

这不起作用的原因是因为您将 my_long_string 声明为函数 f"This is a long string using another {substring} in it." 的 return 值, 而不是 函数本身。

如果您想像示例中那样使用子字符串,则需要将 my_long_string 声明为 lambda : f"This is a long string using another {substring} in it.",这会在 [= 时更改 return 值14=] 改变了。

但正如 Guy 所说,my_long_string.format(substring) 是完全合理的。