我正在编写一个简单的python脚本;我有多个字符串如下所示:
"Some show 14x01 - the one where they do thing 1"
"Some show 14x21 - the one where they do thing 2"
"Some show 10x11 - the one where they do thing 3"
我想替换和附加字符,以便它们的格式如下:
"Some show S14E01 - the one where they do thing 1"
"Some show S14E21 - the one where they do thing 2"
"Some show S10E11 - the one where they do thing 3"
所以理想情况下,我去掉x,用大写E替换x,并在字符串段的前面加上S
我已经找到了正则表达式来识别要修改的部分
r"\d{2}.\d{2}"
或者
r"\d{2}\w\d{2}"
我猜了这么多:
for file in files:
strFileName = str(file)
strFileName = re.sub(r"\d{2}.\d{2}", ) # Unsure here
strNew_name = 'Some show - ' + str(file) # Unsure here
os.rename(file, strNew_name)
但我不知道如何继续和完成这个更名过程。有没有人能帮我找到答案,或是引导我找到一个能帮我回答的问题?谢谢你
您可以创建一个函数来发送到
sub
函数:def replacement (match): return "S" + re.sub(r"[^\d]", "E", match.group(0))
然后将其发送到
sub
函数:strFileName = re.sub(r"\d{2}.\d{2}", replacement, strFileName)
您可以在^{} 中反向引用匹配的组
这里
\1
指第一匹配组,\2
指第二匹配组相关问题 更多 >
编程相关推荐