+ 2

Can anyone clear my doubts on using while and for loops in python?

Can anyone give an example of a program which counts a small string in a bigger string, e.g - big_string = "appleisapple" and i want to count the number of times 'apple' appears in that string, I would like to do it using both while and for loops. s = 'appleisapple' numapp = 0 for x in s: if x == 'apple': numapp += 1 print('Number of App: ' + str(numapp)) The answer always comes 0.

14th Jun 2017, 6:23 AM
Chinmay Sharma
Chinmay Sharma - avatar
2 odpowiedzi
+ 4
""" Try this: s = "appleisapple" for x in s: print(x) ... and you should see your mistake: you are iterating on each char of your string, so you never reach the expected condition x=='apple' ;) What you can do for succeed your custom loop search, is to iterate on indexes rather on values in your tested string and use splicing notation of Python to compare substring of same length as your searched string: the other ways are most efficient, but I guess you want to resolve your case as a training/learning step ^^ """ s = 'appleisapple' numapp = 0 for x in range(len(s)): if s[x:x+len('apple')] == 'apple': numapp += 1 print('Number of App: ' + str(numapp))
14th Jun 2017, 9:37 AM
visph
visph - avatar
0
so i can't use loops? in case i want to find number of bob in s = 'azcbobobegghakl', which is 2, but this string.count gives me only 1, how to solve it?
14th Jun 2017, 6:55 AM
Chinmay Sharma
Chinmay Sharma - avatar