本文介绍了使用正则表达式替换命令在文件名字符串中的小于10的数字前插入前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚如何使用替代命令来完成这项工作,这是我被指示要做的.我将此文本用作变量:

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'

我想搜索文本并在小于10的任何数字前用零代替.我以为我可以做到,如果语句取决于re.match或findall在文本后只能找到一位数字,但我似乎无法执行.这是我的开始代码,在这里我试图将字符串和数字提取到组中,并且只用一位数字提取那些文件名:

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)

但是它不起作用

推荐答案

您可以使用:

re.sub('[a-zA-Z]\d,', lambda x: x.group(0)[0] + '0' + x.group(0)[1:], s)

这篇关于使用正则表达式替换命令在文件名字符串中的小于10的数字前插入前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 10:12