Finding subsequence (nonconsecutive)

后端 未结 4 916
孤城傲影
孤城傲影 2020-11-29 10:18

If I have string needle and I want to check if it exists contiguously as a substring in haystack, I can use:

if needle in          


        
4条回答
  •  一个人的身影
    2020-11-29 10:59

    Another possibility: You can create iterators for both, needle and haystack, and then pop elements from the haystack-iterator until either all the characters in the needle are found, or the iterator is exhausted.

    def is_in(needle, haystack):
        try:
            iterator = iter(haystack)
            for char in needle:
                while next(iterator) != char:
                    pass
            return True
        except StopIteration:
            return False
    

提交回复
热议问题