Every line of 'find all occurrences of a substring in a string python' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.
1 def substrings(string): 2 result = [string] 3 for length in range(1, len(string)): 4 start = 0 5 end = start + length 6 while end <= len(string): 7 result.append(string[start:end]) 8 start += 1 9 end += 1 10 return result
Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code
29 def test_you_can_get_a_substring_from_a_string(self): 30 string = "Bacon, lettuce and tomato" 31 self.assertEqual('let', string[7:10])
15 def search(string, word): 16 """ 17 Searches for occurrences of a "word" within a main "string" by employing 18 the observation that when a mismatch occurs, the word itself embodies 19 sufficient information to determine where the next match could begin, 20 thus bypassing re-examination of previously matched characters. 21 22 :param string: The string to be searched. 23 :param word: The sub string to be searched for. 24 :rtype: The indices of all occurences of where the substring is found in 25 the string. 26 """ 27 word_length = len(word) 28 string_length = len(string) 29 offsets = [] 30 31 if word_length > string_length: 32 return offsets 33 34 prefix = compute_prefix(word) 35 q = 0 36 for index, letter in enumerate(string): 37 while q > 0 and word[q] != letter: 38 q = prefix[q - 1] 39 if word[q] == letter: 40 q += 1 41 if q == word_length: 42 offsets.append(index - word_length + 1) 43 q = prefix[q - 1] 44 return offsets