你可以试试这个:
>>> import re
>>> text = 'file1 file2 file3'
>>> x = re.sub(r'file([1-9])',r'file0\1',text)
'file01 file02 file03'
[1-9] 周围的括号捕获匹配,它是第一个匹配。你会看到我在替换中使用了\1,意思是比赛中的第一个接球。
另外,如果您不想为 2 位或更多位的文件添加零,您可以在正则表达式中添加 [^\d]:
x = re.sub(r'file([1-9](\s|$))',r'file0\1',text)
现在我正在使用str.format() 和lambda 表达式重新访问此答案,因此提供了更多通用解决方案:
import re
fmt = '{:03d}' # Let's say we want 3 digits with leading zeroes
s = 'file1 file2 file3 text40'
result = re.sub(r"([A-Za-z_]+)([0-9]+)", \
lambda x: x.group(1) + fmt.format(int(x.group(2))), \
s)
print(result)
# 'file001 file002 file003 text040'
关于 lambda 表达式的一些细节:
lambda x: x.group(1) + fmt.format(int(x.group(2)))
# ^--------^ ^-^ ^-------------^
# filename format file number ([0-9]+) converted to int
# ([A-Za-z_]+) so format() can work with our format
我使用表达式[A-Za-z_]+ 假设文件名仅包含训练数字之外的字母和下划线。如果需要,请选择更合适的表达方式。