Python Forum
Substring in a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Substring in a string
#1
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 ?
Reply
#2
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?
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Finding how many times substring is in a string using re module ranbarr 4 2,961 May-21-2021, 06:14 PM
Last Post: nilamo
  Find a substring in a dictonary; value substring of key aapurdel 2 7,053 May-31-2019, 06:14 PM
Last Post: ichabod801
  Python: Returning the most frequently occurring substring in a larger string sskkddrit 2 3,889 Feb-09-2018, 06:41 AM
Last Post: sskkddrit
  [Discussion] Re. Substring counting Mekire 9 5,291 Jan-22-2018, 01:56 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020