简体   繁体   中英

Python: Use key of formatting string multiple times

I have a formatting string:

test = 'I am a string and {key}'

Now I want to use the key of this string multiple times to change the string dynamically:

test = test.format(key="hello1")
print(test)
test = test.format(key="hello2")
print(test)

After this I get a KeyError: "key" because the key "key" is overwritten. How can I access the key multiple times without copying the string by copy(test) and without renaming the string? Is there another way to format a string and keep the key?

Edit: The ultimate answer to your question is no . You cannot overwrite a variable with different data then re-use that variable as if you didn't change anything. To my knowledge, no language would allow syntax like this, as it's illogical.

When you declare a variable with test = , you are assigning test to a memory location. When you re-declare with test.format , you're assigning test to an entirely different memory location. Proof:

test = 'I am a string and {key}'
print(id(test))

test = test.format(key="hello1")
print(id(test))

> 1550435806864
> 1550435807104

Could you theoretically store the original memory location and grab that? Maybe, if garbage collection hasn't already cleaned up that location. Should you? Absolutely not. I'd guess trying to do that would lead to a memory leak.


Original Answer

You're overwriting your template string with an entirely new string. Try this instead:

template = 'I am a string and {key}'

test = template.format(key="hello")
print(test)
test = template.format(key="goodbye")
print(test)

In addition to what @SamMorgan said, if you want multiple outputs just use a while or a for loop instead of typing it repetitively. for example, for a defined number of times, use for loop-


    test='this is a {key}'
    for i in range(5):
        c=input()
        print(test.format(key=c))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM