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:
JavaScript
x
9
1
substring = ""
2
my_long_string = f"This is a long string using another {substring} in it."
3
4
def printMyString(newString):
5
substring = newString
6
print(my_long_string)
7
8
printMyString(newString="newer, better substring")
9
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:
JavaScript
1
10
10
1
substring = ""
2
3
def regenerate_string(substring):
4
return f"This is a long string using another {substring} in it."
5
6
def printMyString(newString):
7
print(regenerate_string(newString))
8
9
printMyString(newString="newer, better substring")
10
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
JavaScript
1
5
1
my_long_string = "This is a long string using another {} in it."
2
3
print(my_long_string.format("newer, better substring")) # This is a long string using another newer, better substring in it.
4
print(my_long_string.format("some other substring")) # This is a long string using another some other substring in it.
5
You can insert as many substrings as you want that way
JavaScript
1
3
1
string = "With substrings, this {} and this {}."
2
print(string.format("first", "second")) # With substrings, this first and this second.
3
You can also use variables
JavaScript
1
4
1
string = "With substrings, this {foo} and this {bar}."
2
print(string.format(foo="first", bar="second")) # With substrings, this first and this second.
3
print(string.format(bar="first", foo="second")) # With substrings, this second and this first.
4