[英]Python - can you “refresh” a variable to re-initialize with new sub-variables?
假设我想声明一个字符串供整个班级使用,但该字符串有一部分可能会在以后更改。 是否可以只声明一次字符串,然后“刷新”它?
例子:
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."
的返回值f"This is a long string using another {substring} in it."
,而不是函数本身。
如果您想在示例中使用您打算使用的子字符串,则需要将my_long_string
声明为lambda : f"This is a long string using another {substring} in it."
,这会在substring
更改时更改返回值。
但就像盖伊说的, my_long_string.format(substring)
是完全合理的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.