如何使用python正则表达式将字符串数据附加到特定位置?

2024-10-01 19:19:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个简单的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)

但我不知道如何继续和完成这个更名过程。有没有人能帮我找到答案,或是引导我找到一个能帮我回答的问题?谢谢你


Tags: the字符串hereshowsomewheredoone
2条回答

您可以创建一个函数来发送到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)

您可以在^{}中反向引用匹配的组

>>> 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指第二匹配组

相关问题 更多 >

    热门问题