第一步:可以使用正则表达式
regex = re.compile(r'\d+')
regex.findall(filename)
这将返回包含数字的字符串列表。
[int(x) for x in regex.findall(filename)]
如果每个文件名中只有一个数字,则可以使用regex.search(filename).group(0)(如果您确定它将产生匹配)。
如果没有找到匹配项,上面的行将生成一个attributeError,表示NoneType没有attributegroup。
import re name = 'CP_epoch264.pth' regex = re.compile(r'\d+') num = int(max(regex.findall(name))) print(num)
注意:regex.findall(name)返回值是list,所以通过max函数取值并取整。