s="hellohel"
sub="hel"
count=0
for i in s:
if sub in s:
present = True
count =1
else:
present = False
I am getting output: True 8 The output should be:True 2
print(present,count)
CodePudding user response:
Your code currently checks, for each character in hellohel, if hel is in hellohel. As it stands, hel is always in hellohel, so that will always be true. That means, your count will in practice count how many characters there are in hellohel.
Perhaps what you're looking for is something along the lines of
s = "hellohel"
sub = "hel"
count = 0
present = False
for i in range(len(s)):
if (s[i:i len(sub)] == sub):
count = 1
present = True
print(count, present) # Prints 2 True
This code needs to be cleaned up somewhat, and there are some optimization that can be done. However, this should help push you in the right direction.
CodePudding user response:
So the reason why it showing is because of the for loop "for i in s:", as your string has 8 "hellohel" places. So whenever you try to run the for loop it runs 8 times.
CodePudding user response:
s="hellohel"
sub="hel"
count=0
for i in s: # this line iterates through each character the string "s" (8 times), assigning the current character to i
if sub in s: # this line is just checking whether "hel" is in "hellohel" once for every character in "hellohel"
present = True
count =1 # that means it will count to 8 every time, because "hel" is always in "hellohel"
else:
present = False
Overall, not the correct way to approach it. There are multiple answers here that don't use .count() but that use re, or nothing but vanilla python. Count number of occurrences of a substring in a string