删除带有数字和字符串之间破折号的子字符串

removing a sub string with digits and a dash in between a string

我一直在尝试从字符串中删除带有数字的子字符串,但没有成功

字符串:

All in the Family 01-01 - Meet the Bunkers.mp4

想要的结果:

All in the Family - Meet the Bundkers.mp4

请记住,我正在尝试 运行 此代码:

import os
import re

templist = []
templist1 = []
templist2 = []
numlist = []

for root, dirs, files in os.walk("E:\Plex Content\TV Shows\All in the Family (Complete TV Series in MP4 format)"):
    for file in files:
        templist.append(file.replace(' ' + r'\d\d' + '-' + r'\d\d' + ' ', ''))

print(templist)

如有任何帮助,我们将不胜感激

谢谢,

小吉弗

我不知道你的代码是怎么回事,但如果唯一的要求是删除数字和中间的“-”,我会这样做

import re
s = "All in the Family 01-01 - Meet the Bunkers.mp4"
pattern = '[0-9]'
s = re.sub(pattern, '', s[:-4]) + s[-4:]
s = s.replace("-","",1)
print(s)
  • 输出:全家福 - 认识地堡.mp4

假设您要删除两个数字,然后是一个破折号,然后是两个数字和白色 space,以下正则表达式替换有效:

re.sub(r"\d{2}-\d{2}\s", "", file)
#'All in the Family - Meet the Bunkers.mp4'

在使用模式之前,编译它以加快工作速度很有用。

patern = re.compile(r'\d+-\d+\s*')
file = patern.sub("", file)
#'All in the Family - Meet the Bunkers.mp4'