Say I have strings like (outputted from running glob.glob()
on output from someone else's code):
image-0.png
image-1.png
image-2.png
image-3.png
image-4.png
image-5.png
image-6.png
image-7.png
image-8.png
image-9.png
image-10.png
image-11.png
How do I left zero pad the integer substring within each string?
Related questions:
Not using python - Zero-pad numbers within a string
You can use regular expression to achieve your goal.
import re
files = [
"image-0.png",
"image-1.png",
"image-2.png",
"image-3.png",
"image-4.png",
"image-5.png",
"image-6.png",
"image-7.png",
"image-8.png",
"image-9.png",
"image-10.png",
"image-11.png"
]
def pad_image_filename(filename):
return re.sub(r'(\d+)', lambda x: x.group(1).zfill(2), filename)
padded_files = [pad_image_filename(f) for f in files]
print(padded_files) # ['image-00.png', 'image-01.png', 'image-02.png', 'image-03.png', 'image-04.png', 'image-05.png', 'image-06.png', 'image-07.png', 'image-08.png', 'image-09.png', 'image-10.png', 'image-11.png']
r'(\d+)'
matches 1 or more digits in the string. In this case, it matches 0
, 1
, 2
, ..., 11
in the file names.
group(1)
returns the string matched by the first capturing group in the regular expression.
zfill(2)
zero-pads the matched strings to 2 digits.
You can find the documentation of re.sub()
here.