【问题标题】:How to chain multiple re.sub() commands in Python [duplicate]如何在 Python 中链接多个 re.sub() 命令
【发布时间】:2018-03-01 21:33:18
【问题描述】:

我想对一个字符串进行多次 re.sub() 替换,并且每次都替换为 不同的 字符串。

当我有很多子字符串要替换时,这看起来很重复。有人可以建议一个更好的方法吗?

stuff = re.sub('__this__', 'something', stuff)
stuff = re.sub('__This__', 'when', stuff)
stuff = re.sub(' ', 'this', stuff)
stuff = re.sub('.', 'is', stuff)
stuff = re.sub('__', 'different', stuff).capitalize()

【问题讨论】:

  • @Rawing,谢谢,这样更好。我的搜索没有显示,因为我有 re.sub()。将删除。
  • 等等,实际上我应该保留这个q,因为它的措辞不同,还是删除它,因为它是重复的?
  • 老实说,我认为不值得保留。但如果不想删除,也可以将其作为副本关闭。
  • 是的,我将只使用 str.replace() 代替。所以不会让我关闭它。哈。

标签: python regex


【解决方案1】:

将搜索/替换字符串存储在列表中并循环遍历它:

replacements = [
    ('__this__', 'something'),
    ('__This__', 'when'),
    (' ', 'this'),
    ('.', 'is'),
    ('__', 'different')
]

for old, new in replacements:
    stuff = re.sub(old, new, stuff)

stuff = stuff.capitalize()

请注意,当您要替换文字 . 字符时,您必须使用 '\.' 而不是 '.'

【讨论】:

  • 我假设它之前已经定义过,就像在原始代码中一样。
  • 但是re.sub 之前没有被调用过。 stuff 只是开头的原始字符串。
  • 啊,你的权利。我误读了OP的帖子。出于某种原因,我的大脑将“stuff”替换为“string”...... now 回顾我的答案,我仍然认为它非常愚蠢。对于 OP 的用例,你的显然更好。对此感到抱歉。
【解决方案2】:
tuple = (('__this__', 'something'),('__This__', 'when'),(' ', 'this'),('.', 'is'),('__', 'different'))

for element in tuple:
    stuff = re.sub(element[0], element[1], stuff)

【讨论】:

    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多