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
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'
You can use:
re.sub('[a-zA-Z]\d,', lambda x: x.group(0)[0] + '0' + x.group(0)[1:], s)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With