1
entrada = str(input().lower())

replace = "mem".lower()
find = entrada.lower()
count = 0
while (entrada.find(replace) != -1):
   entrada = entrada.replace(replace, "", 1)
   count +=1

print(count) 

No count,list or lambda can be used. I'm suposed to make a program that receives a lower string from the user then finds, counts and print the number of times a substring appeared. But I'm having problems with overlapping strings.

example: string is memem, the expected exit is 2

3
  • First I'm not sure why you're casting to string after lower. if input is not string, lower will most likely throw an AttributeError. Also my question - the user provides both the substring and string? Commented Apr 24, 2015 at 17:50
  • Only string and it has to be lower Commented Apr 24, 2015 at 17:50
  • have you tried my approach from your other thread? oops, Sorry that wasn't you. Commented Apr 24, 2015 at 17:59

2 Answers 2

3

One way to do this is to use the second argument of str.find which indicates an optional index to start searching for the substring within a string.

From the docs:

str.find(sub[, start[, end]])¶ Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

So if we keep track of the last_index found in a variable, we can simply start the search for the substring again in the next possible index. Expressed in code, this is the expression last_index + 1. If last_index is ever -1, we stop searching for the substring and output our count:

mystr = 'memem'
mysubstr = 'mem'
count = 0
last_index = -1
while True:
    last_index = mystr.find(mysubstr, last_index + 1)
    if last_index == -1:
        break
    count += 1

print(count)
Sign up to request clarification or add additional context in comments.

Comments

0

You could use

i = 0
while True:
    i = entrada.find(replace, i) + 1
    if i:
         count += 1
    else:
        break

This will then find replace in entrada, increment the count, find replace in entrada[i+1:] where i is the start of the previous match, increment the count, and repeat forever.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.