【问题标题】:How to remove all characters before a specific character in Python?如何删除Python中特定字符之前的所有字符?
【发布时间】:2015-09-05 21:18:26
【问题描述】:

我想删除指定字符或字符集之前的所有字符(例如):

intro = "<>I'm Tom."

现在我想删除I'm 之前的&lt;&gt;(或者更具体地说,I)。有什么建议吗?

【问题讨论】:

  • 指定字符是什么?
  • @SimeonVisser 在这种情况下,它是I
  • 我明白了,但在其他情况下呢?我们怎么知道文本从哪里开始?
  • 好吧,我正在过滤我在文本中寻找的内容;因此,作为回应,您可以通过使用循环、拆分文本/单词等来知道它从哪里开始。

标签: python string replace


【解决方案1】:

使用re.sub。只需将所有字符匹配到I,然后将匹配的字符替换为I

re.sub(r'^.*?I', 'I', stri)

【讨论】:

  • 我对@9​​87654325@ 还很陌生,我会再研究一下;感谢您的回答,谢谢!
  • 请注意,您可以在第一个或最后一个 I re.sub(r'.*?I', 'I', stri) 之间切换。但其他答案不能满足这一点。
  • 所以你说re 是最好的选择?你有什么好的教程/文章来解释re 的基本原理吗?感谢您的帮助。
  • 选择答案完全取决于您。是的,学习正则表达式是每个开发人员都必须学习的,因为只有少数语言不会使用正则表达式。
  • @AvinashRajdo 你知道我怎么能在不知道长度或字符的情况下做到这一点吗?
【解决方案2】:

str.find可以找到certain string's first appearance的字符索引:

intro[intro.find('I'):]

【讨论】:

  • 如果字符串中缺少字符,这将只返回输入字符串的最后一个字符,因为.find 将返回-1,而some_str[-1:] 是“返回从最后一个字符开始的所有字符一个”。
【解决方案3】:

由于index(char) 为您获取字符的第一个索引,您可以简单地使用string[index(char):]

例如,在这种情况下 index("I") = 2intro[2:] = "I'm Tom."

【讨论】:

  • 没问题。这也适用于任何字符串。请注意,1)您可能必须确保索引有效,即不是 -1 和 2)index 仅返回给定字符串的第一次出现。
  • 实际例子是:intro[intro.index('I'):]
  • 如果字符没有出现在字符串中,这将引发ValueError
【解决方案4】:

如果你知道从哪里开始删除的字符位置,你可以使用切片表示法:

intro = intro[2:]

如果您知道要删除的字符,而不是知道从哪里开始,那么您可以使用lstrip() 函数:

intro = intro.lstrip("<>")

【讨论】:

    【解决方案5】:
    str = "<>I'm Tom."
    temp = str.split("I",1)
    temp[0]=temp[0].replace("<>","")
    str = "I".join(temp)
    

    【讨论】:

    • 不是反对者,但你可以使用这个'I' + intro.split('I', 1)[1]
    • @AvinashRaj 我也不是,尽管(真的很好奇)这会如何以不同的方式塑造函数?据我了解,您在I? 之前拆分所有内容?还有,[1] 代表什么?
    • 拆分列表的索引1
    【解决方案6】:

    我遍历了字符串并传递了索引。

    intro_list = []
    
    intro = "<>I'm Tom."
    for i in range(len(intro)):
        if intro[i] == '<' or intro[i] == '>':
            pass
        else:
            intro_list.append(intro[i])
    
    intro = ''.join(intro_list)
    print(intro)
    

    【讨论】:

      【解决方案7】:
      >>> intro = "<>I'm Tom."
      #Just split the string at the special symbol
      
      >>> intro.split("<>")
      
      Output = ['', "I'm Tom."]
      
      >>> new = intro.split("<>")
      
      >>> new[1]
      "I'm Tom."
      

      【讨论】:

        【解决方案8】:
        import re
        
        date_div = "Blah blah\nblah, Updated: Aug. 23, 2012 Blah blah Updated: Feb. 13, 2019"
        
        up_to_word = ":"
        rx_to_first = r'^.*?{}'.format(re.escape(up_to_word))
        rx_to_last = r'^.*{}'.format(re.escape(up_to_word))
        
        # (Dot.) In the default mode, this matches any character except a newline. 
        # If the DOTALL flag has been specified, this matches any character including a newline.
        
        print("Remove all up to the first occurrence of the word including it:")
        print(re.sub(rx_to_first, '', date_div, flags=re.DOTALL).strip())
        
        print("Remove all up to the last occurrence of the word including it:")
        print(re.sub(rx_to_last, '', date_div, flags=re.DOTALL).strip())
        

        【讨论】:

          【解决方案9】:

          如果字符也不在字符串中,则此解决方案有效,但使用可能很慢的 if 语句。

          if 'I' in intro:
            print('I' + intro.split('I')[1])
          else:
            print(intro)
          

          【讨论】:

            【解决方案10】:
            import re
            intro = "<>I'm Tom."
            re.sub(r'<>I', 'I', intro)
            

            【讨论】:

            • 不会删除指定字符 (OP) 之前的所有内容,例如使用intro = "junk&lt;&gt;I'm Tom.",产生"junkI'm Tom."
            猜你喜欢
            • 1970-01-01
            • 2017-04-16
            • 2015-01-26
            • 2010-10-28
            • 1970-01-01
            • 2016-07-06
            • 2016-10-15
            相关资源
            最近更新 更多