Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading