Skip to content
Advertisement

Python – can you “refresh” a variable to re-initialize with new sub-variables?

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?

Advertisement

Answer

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.
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement