簡體   English   中英

Python - 您可以“刷新”一個變量以使用新的子變量重新初始化嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM