你可以试试这个:>>> import re
>>> text = 'file1 file2 file3'
>>> x = re.sub(r'file([1-9])',r'file0\1',text)
'file01 file02 file03'
包装在[1-9]周围的括号捕获匹配,这是第一个匹配。您将看到我在replace中使用它,使用\1表示匹配中的第一个catch。
另外,如果不想为2位或更多的文件添加零,可以在regexp中添加[^\d]:x = re.sub(r'file([1-9](\s|$))',r'file0\1',text)
现在我使用^{}和^{}表达式重新讨论这个答案,这是一个更通用的解决方案: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_]+,假设文件名除了训练数字之外,还包含字母和下划线。如果需要,请选择更合适的表达式。