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 do I use python to zero pad an integer substring (not a whole string) within another string?

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:

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

Not using python – Zero-pad numbers within a string

>Solution :

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 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.

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