John Hon John Hon - 2 months ago 6
Python Question

Why don't string variables update when they are changed

Say we have some code like so :

placehold = "6"
string1 = "this is string one and %s" % placehold

print string1

placehold = "7"
print string1


When run, both of the print statements return as if placehold were ALWAYS 6. However, just before the second statement ran, placehold was changed to 7, so why does it not dynamically reflect in the string?

Also, would you be able to suggest a way to make the string return with 7?

Thank you

Answer

When you do:

string1 = "this is string one and %s" % placehold

You are creating a string string1 with %s replaced by the value of placehold On later changing the value of placehold it won't have any impact on string1 as string does not hold the dynamic property of variable. In order to reflect the string with changed value, you have to again re-assign the string.

Alternatively, you may use .format() as:

string1 = "this is string one and {}"
placeholder = 6
print string1.format(placeholder)
# prints: this is string one and 6

placeholder = 7
print string1.format(placeholder)
# prints: this is string one and 7
Comments