Say i want to declare a string for my entire class to use, but that string has a part that might change later. Is it possible to only have to declare the string once, and "refreshing" it later?
Example:
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")
Can i adjust this code so that in the end, it prints out This is a long string using another newer, better substring in it.
, without declaring the long string again later on?
My only guess would be something like this:
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")
But i want to ask if there possibly is a built-in function in Python to do exactly that?
Don't use f-string
, declare the template string with place holder {}
and use format()
where necessary
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.
You can insert as many substrings as you want that way
string = "With substrings, this {} and this {}."
print(string.format("first", "second")) # With substrings, this first and this second.
You can also use variables
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.
The reason this doesn't work is because you declare my_long_string
as the return value from the function f"This is a long string using another {substring} in it."
, not the function itself.
If you want to use the substring like you intended to in your example, you would need to declare my_long_string
to be lambda : f"This is a long string using another {substring} in it."
, which would change return values when substring
changed.
But like Guy said, my_long_string.format(substring)
is perfectly reasonable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.