Home > Software design >  How to format a string to a new string without changing the original?
How to format a string to a new string without changing the original?

Time:09-09

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?

CodePudding user response:

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'

CodePudding user response:

No, it won't. String is immutable in python means once assigned, it cannot be replaced. Consider this for your example:

s = "worker-{0}"
s1 = s.format(1)
s2 = s.format(2)
print(s)
print(s1, s2)

The output will be:

worker-{0}

worker-1 worker-2

CodePudding user response:

Strings are immutable hence at each modification a new instance is created, see why string are immutable.

n = 5
WORKER_TEMPLATE = "worker-{}"  # <- without 0
workers = list(map(WORKER_TEMPLATE.format, range(n)))

print(workers)
#['worker-0', 'worker-1', 'worker-2', 'worker-3', 'worker-4']

Remark: the following are equivalents:

s1 = "{} & {}"  
print(s1.format('a', 'b'))

and

s2 = "{0} & {1}"  
print(s2.format('a', 'b'))

A possible advantage of the "place-holder" notation are multiple substitution of the same value:

print("{0} & {1} {0}".format('a', 'b'))
#a & b a
  • Related