Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Substring Counting
#2
Welcome to the forum, please use code tags in the future around your code (the python button you see when posting).

Seems your answer is almost correct except you are setting x to 0 every time through the loop.
With that outside the loop it seems to work:
x = 0
for s,_ in enumerate(haystack):
    haysub = haystack[s:len(needle) + s]
    if haysub == needle:
        x += 1

print(x)
Reply


Messages In This Thread
Substring Counting - by shelbyahn - Jan-20-2018, 02:16 AM
RE: Substring Counting - by Mekire - Jan-20-2018, 04:36 AM
RE: Substring Counting - by krisputas - Jan-13-2022, 10:08 AM
RE: Substring Counting - by shelbyahn - Jan-21-2018, 05:20 PM
RE: Substring Counting - by j.crater - Jan-21-2018, 05:40 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  extract substring from a string before a word !! evilcode1 3 700 Nov-08-2023, 12:18 AM
Last Post: evilcode1
  [SOLVED] [regex] Why isn't possible substring ignored? Winfried 4 1,238 Apr-08-2023, 06:36 PM
Last Post: Winfried
  ValueError: substring not found nby2001 4 8,281 Aug-08-2022, 11:16 AM
Last Post: rob101
  Match substring using regex Pavel_47 6 1,589 Jul-18-2022, 07:46 AM
Last Post: Pavel_47
  Python Substring muzikman 4 2,457 Dec-01-2020, 03:07 PM
Last Post: deanhystad
  Removing items from list if containing a substring pythonnewbie138 2 2,316 Aug-27-2020, 10:20 PM
Last Post: pythonnewbie138
  Substring and If then Condition to create column Chandan 2 2,455 Jan-23-2020, 08:40 AM
Last Post: buran
  ValueError: substring not found hoangthai10788 2 4,743 Sep-23-2019, 05:34 PM
Last Post: ichabod801
  Substring extraction nevendary 6 4,164 Apr-24-2019, 05:41 AM
Last Post: nevendary
  substring between substrings Skaperen 5 4,332 Oct-27-2018, 08:45 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

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