Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using regular expression substitution command to insert leading zeros in front of numbers less than 10 in a string of filenames

I am having trouble figuring out how to make this work with substitution command, which is what I have been instructed to do. I am using this text as a variable:

text = 'file1, file2, file10, file20'

I want to search the text and substitute in a zero in front of any numbers less than 10. I thought I could do and if statement depending on whether or not re.match or findall would find only one digit after the text, but I can't seem to execute. Here is my starting code where I am trying to extract the string and digits into groups, and only extract the those file names with only one digit:

import re
text = 'file1, file2, file10, file20'
mtch = re.findall('^([a-z]+)(\d{1})$',text)

but it doesn't work

like image 356
kflaw Avatar asked Aug 12 '13 16:08

kflaw


2 Answers

You can use re.sub with str.zfill:

>>> text = 'file1, file2, file10, file20'
>>> re.sub(r'(\d+)', lambda m : m.group(1).zfill(2), text)
'file01, file02, file10, file20'
#or
>>> re.sub(r'([a-z]+)(\d+)', lambda m : m.group(1)+m.group(2).zfill(2), text)
'file01, file02, file10, file20'
like image 125
Ashwini Chaudhary Avatar answered Sep 23 '22 13:09

Ashwini Chaudhary


You can use:

re.sub('[a-zA-Z]\d,', lambda x: x.group(0)[0] + '0' + x.group(0)[1:], s)
like image 41
Saullo G. P. Castro Avatar answered Sep 22 '22 13:09

Saullo G. P. Castro