Reputation: 333
oldName = "old_###"
now I want to convert all the "#" in to the serial number, for example, in this case oldName should be "old_001"
is there any possible Pythonic Way to do this?
Upvotes: 0
Views: 1150
Reputation: 177685
If ###
isn't a requirement:
print 'old_{:03d}'.format(1)
If you need ###
, here's a way to compute the format string:
import re
name = "old_#####"
fmt = re.sub(r'#+',lambda m: r'{{:0{}d}}'.format(len(m.group(0))),name)
print name
print fmt
for i in range(5):
print fmt.format(i)
old_#####
old_{:05d}
old_00000
old_00001
old_00002
old_00003
old_00004
Upvotes: 1
Reputation: 4224
oldName = "old_{serial_number}"
oldName.format(serial_numer='001')
Of course, this assumes that you do not really have to use '#'.
Upvotes: 1
Reputation: 35059
Try it with string formatting:
number = 123
serial_number = "old_%03d" % number
Upvotes: 1
Reputation: 670
Couldn't you just do:
oldName.replace('###', '001')
Of course my assumption here is that you always have 3 '#' symbols.
Simple is the best way to go I say, if this works you won't need to use the re
module.
Upvotes: 3