【问题标题】:Removing from a string all the characthers included between two specific characters in Python从字符串中删除包含在 Python 中两个特定字符之间的所有字符
【发布时间】:2018-01-20 15:05:38
【问题描述】:

在 Python 中,从 字符串 中取出两个特定 字符 之间包含的所有 字符 的快速方法是什么?

【问题讨论】:

  • 你看过re module和正则表达式吗?
  • 这是微不足道的。下次尝试更好地搜索...
  • 你能告诉我们你期望的结果字符串吗?
  • @GalAbra 这行不通

标签: python regex


【解决方案1】:

您可以使用这个正则表达式:\(.*?\)。在这里演示:https://regexr.com/3jgmd

然后您可以使用此代码删除该部分:

import re
test_string = 'This is a string (here is a text to remove), and here is a text not to remove'
new_string = re.sub(r" \(.*?\)", "", test_string)

这个正则表达式 (regex) 将在括号中查找任何文本(不带换行符),括号中带有空格

【讨论】:

    【解决方案2】:

    你很可能会使用像这样的正则表达式

    \s*\([^()]*\)\s*
    

    为此(请参阅a demo on regex101.com)。
    该表达式会删除括号中的所有内容和周围的空格。


    Python 中,这可能是:
    import re
    test_string = 'This is a string (here is a text to remove), and here is a text not to remove'
    new_string = re.sub(r'\s*\([^()]*\)\s*', '', test_string)
    print(new_string)
    # This is a string, and here is a text not to remove
    


    但是,出于学习目的,您也可以使用内置方法:
    test_string = 'This is a string (here is a text to remove), and here is a text not to remove'
    left = test_string.find('(')
    right = test_string.find(')', left)
    
    if left and right:
        new_string = test_string[:left] + test_string[right+1:]
        print(new_string)
        # This is a string , and here is a text not to remove
    

    后者的问题:它不考虑多次出现并且不删除空格,但它肯定更快。


    每次执行 100k 次,测量结果:
    0.578398942947 # regex solution
    0.121736049652 # non-regex solution
    

    【讨论】:

      【解决方案3】:

      要删除 () 中的所有文本,您可以使用 re 中的 findall() 方法并使用 replace() 删除它们:

      import re
      test_string = 'This is a string (here is a text to remove), and here is a (second one) text not to remove'
      remove = re.findall(r" \(.*?\)",test_string)
      for r in remove:
          test_string = test_string.replace(r,'')
      print(test_string)
      #result: This is a string , and here is a  text not to remove
      

      【讨论】:

        猜你喜欢
        • 2017-10-24
        • 1970-01-01
        • 2015-07-23
        • 2015-01-26
        • 2016-01-02
        • 2011-06-23
        • 2014-09-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多