【问题标题】:How to remove a substring after a substring?如何在子字符串之后删除子字符串?
【发布时间】:2021-08-26 04:57:19
【问题描述】:

我有以下字符串:

somestring = "Zero function argument 1 since code 345 and from code 8476 then it goes on"

我想删除 since code 345from code 8476(这些数字可能会有所不同),但我想在字符串中保留 argument 1 中的 1

我正在做以下事情:

import re

somestring = "Zero function argument 1 since code 345 and from code 8476 then it goes on"
somestring = somestring.replace("since code", "").replace("from code", "")
stringlist = somestring.split(" ")
pattern = '[0-9]'
print([re.sub(pattern, "", i) for i in stringlist])

但输出会从字符串中的argument 1 中删除1。输出如下所示: ['Zero', 'function', 'argument', '', '', '', 'and', '', '', 'then', 'it', 'goes', 'on']

但我想要的理想输出是Zero function argument 1 and then it goes on,即删除since codefrom code之后的任何数字,删除“since code”和“from code”,并且在字符串或列表中没有'' .

如何做到这一点?

【问题讨论】:

    标签: python python-3.x regex string


    【解决方案1】:

    我会在这里使用正则表达式替换:

    somestring = "Zero function argument 1 since code 345 and from code 8476 then it goes on"
    output = re.sub(r'\s*\b(?:since|from) code \d+\s*', ' ', somestring).strip()
    print(output)  # Zero function argument 1 and then it goes on
    

    【讨论】:

      【解决方案2】:

      我想这就是你所追求的:

      import re
      
      somestring = "Zero function argument 1 since code 345 and from code 8476 then it goes on"
      result = re.sub(r'(?:since|from) code \d+ ', '', somestring)
      print(result)
      

      请注意,\d+ 之后有一个空格,因为在您的示例中,您要替换的字符串之前和之后都有空格。例如,如果短语since code 123 也可以出现在引号中,或者在逗号或句点之前,那么您可能需要这样的内容:

      import re
      
      somestring = "Zero function argument 1 since code 345, and from code 8476 as well. Then it goes on"
      result = re.sub(r'\s*(?:since|from) code \d+\s*', ' ', somestring)
      print(result)
      

      (与@TimBiegeleisen 发布的内容非常相似)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-20
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-23
        • 2015-08-07
        相关资源
        最近更新 更多