我正在编写一个简单的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"
因此,理想情况下,我将删除用大写 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)
但我不知道如何继续和完成这个重命名过程。有人可以帮助指导我找到答案或指导我找到一个已提出的问题来帮助我回答吗?谢谢!
最佳答案
您可以反向引用 re.sub
中的匹配组
>>> import re
>>> s = "Some show 14x01 - the one where they do thing 1"
>>> re.sub(r"(\d{2}).(\d{2})", r"S\1E\2",s)
>>> 'Some show S14E01 - the one where they do thing 1'
这里 \1
指的是第一个匹配组,\2
指的是第二个匹配组。
关于python - 如何使用 python 正则表达式将字符串数据附加到某些位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216652/