【问题标题】:How can I remove everything in a string until a character(s) are seen in Python如何删除字符串中的所有内容,直到在 Python 中看到一个字符
【发布时间】:2016-01-13 12:02:22
【问题描述】:

假设我有一个字符串,我想在看到某些字符之前或之后删除字符串的其余部分

例如,我所有的字符串中都有'egg':

"have an egg please"
"my eggs are good"

我想得到:

"egg please"
"eggs are good"

还有同样的问题,但我怎样才能删除除了字符前面的字符串之外的所有内容?

【问题讨论】:

    标签: python python-3.x string python-2.7


    【解决方案1】:

    您可以使用str.find 方法和一个简单的索引:

    >>> s="have an egg please"
    >>> s[s.find('egg'):]
    'egg please'
    

    请注意,str.find 如果找不到子字符串,将返回 -1,并将返回字符串的最后一个字符。因此,如果您不确定您的字符串是否始终包含子字符串,您最好使用前检查str.find 的值。

    >>> def slicer(my_str,sub):
    ...   index=my_str.find(sub)
    ...   if index !=-1 :
    ...         return my_str[index:] 
    ...   else :
    ...         raise Exception('Sub string not found!')
    ... 
    >>> 
    >>> slicer(s,'egg')
    'egg please'
    >>> slicer(s,'apple')
    Sub string not found!
    

    【讨论】:

    • 值得注意——如果没有找到子字符串,find 将返回-1,从而输出主字符串的最后一个字符(例如上面的e)。另一种选择是将find替换为index,这类似于find,但如果找不到子字符串,则会引发ValueError,然后相应地处理异常。
    • @DreadPirateShawn 确实,用额外的信息更新了答案。 tnx 引起注意。
    • 不应该是return错误信息而不是打印出来吗?
    • 谢谢你,这是我使用的方法,它现在正在工作。我所做的唯一区别是替换“未找到子字符串!”通过。
    【解决方案2】:
    string = 'Stack Overflow'
    index = string.find('Over') #stores the index of a substring or char
    string[:index] #returns the chars before the seen char or substring
    

    因此,输出将是

    'Stack '
    

    string[index:]
    

    会给

    'Overflow'
    

    【讨论】:

    • 您使用 [:index] 保留第一部分,而 OP 希望保留除此之外的所有内容。用索引切换冒号与问题对齐,
    • 感谢您指出这一点。我会编辑它。
    【解决方案3】:

    使用正则表达式获取子字符串。

    import re
    def slice(str, startWith):
        m = re.search(r'%s.*' % startWith,str) # to match pattern starts with `startWith`
        if not m: return ""#there is no proper pattern, m is None
        else: return m.group(0)
    

    【讨论】:

      【解决方案4】:

      您可以使用str.join()str.partition()

      ''.join('have an egg please'.partition('egg')[1:])
      

      【讨论】:

        【解决方案5】:
        >>> s = "eggs are good"
        >>> word = "eggs"
        >>> if word in s:
                print s.split(word)[1]
        are good
        

        【讨论】:

        • 这不打印拆分器参数 egg
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-16
        相关资源
        最近更新 更多