假设我想声明一个字符串供整个类使用,但该字符串的一部分稍后可能会更改。是否可能只需要声明一次字符串;刷新";晚些时候?
示例:
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."
的返回值,而不是函数本身。
如果要像在示例中那样使用子字符串,则需要将my_long_string
声明为lambda : f"This is a long string using another {substring} in it."
,这将在substring
更改时更改返回值。
但正如盖伊所说,my_long_string.format(substring)
是完全合理的。