How to format a string to a new string without changing the original?

I have an original string: WORKER_TEMPLATE = "worker-{0}" how can I use that template to create: "worker-0", "worker-2" and "worker-N" most efficiently? If I simply use string formatting I will lose the original after the first formatting since it is in place. Is there a way to format a string not in place?

>Solution :

str.format is immutable so it won’t change the original formatted string.

WORKER_TEMPLATE = "worker-{0}"
for i in range(5):
    print(WORKER_TEMPLATE.format(i))
    
worker-0
worker-1
worker-2
worker-3
worker-4

You can also define a generator using the same formatted string:

>>> def get_value(n=5):
...     for i in range(n):
...         yield WORKER_TEMPLATE.format(i)
...         
>>> values = get_value()
>>> next(values)
'worker-0'
>>> next(values)
'worker-1'
>>> next(values)
'worker-2'

Leave a Reply