Python 3.3中的re.sub

use*_*215 3 python regex substitution python-3.x

我想文本字符串从形式变化file1file01.我是python的新手,在尝试使用模式时无法弄清楚应该在'repl'位置进行什么.任何人都可以帮我一把吗?

text = 'file1 file2 file3'

x = re.sub(r'file[1-9]',r'file\0\w',text) #I'm not sure what should go in repl.
Run Code Online (Sandbox Code Playgroud)

Jer*_*rry 7

你可以试试这个:

>>> import re    
>>> text = 'file1 file2 file3'
>>> x = re.sub(r'file([1-9])',r'file0\1',text)
'file01 file02 file03'
Run Code Online (Sandbox Code Playgroud)

围绕的括号[1-9]捕获匹配,这是第一场比赛.您将看到我在替换中使用它\1意味着匹配中的第一个捕获.

此外,如果您不想为2位或更多位数的文件添加零,您可以添加正[^\d]则表达式:

x = re.sub(r'file([1-9](\s|$))',r'file0\1',text)
Run Code Online (Sandbox Code Playgroud)

现在我正在使用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'
Run Code Online (Sandbox Code Playgroud)

关于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
Run Code Online (Sandbox Code Playgroud)

我使用的表达式[A-Za-z_]+假设文件名只包含训练数字以外的字母和下划线.如果需要,请选择更合适的表达方式.