Python Forum
Substring in a string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Substring in a string (/thread-22868.html)



Substring in a string - Propoganda - Nov-30-2019

I need to create a function that counts all the occurrences of a substring in a string and then sort
a dictionary that includes these three features : key must be the substring itself, and the value has to show the indices from which each substring start and the number of occurrences as I've already mentioned before. I'll give you an example and then I'll share my code to see whether I am in the right direction or I must totally change my way of thinking.
the function input is : a given string and a constant length of a substring that I'll have to slice.
Given a string like : 'aabbbcaab' - the matching dictionary for a substring of 3 letters is { 'aab':[0,6],
'bbc' :[3,5]}

Here is my attempt :

def findsubstringlocation(s,k):
 
 substringlocation = {}
 for char in range(0,len(s),k):
    substringlocation[s[char:char+k]]=[]
    substringlocation[s[char:char+k]].append(char)

 return substringlocation

print(findsubstringlocation('aabbccaabb',2))
Any suggestions ?


RE: Substring in a string - perfringo - Dec-01-2019

This description has too much ambiguity or plain contradictions in it.

"key must be the substring itself, and the value has to show the indices from which each substring start and the number of occurrences as I've already mentioned before"

Where is in 'aab':[0,6] number of occurances? Is it zero or six?