Python-您可以“刷新”一个变量以使用新的子变量重新初始化吗?
假设我想声明一个字符串供整个班级使用,但该字符串有一部分可能会在以后更改。是否可以只声明一次字符串,然后“刷新”它?
例子:
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.