You are using the for loop wrong.

This takes each character in the string, assigns it to x, and prints it:

for x in 'aabfh':
    print (x)

This takes each character in the string, assigns it to list1[i], and prints it:

for list1[i] in 'aabfh':
    print(list1[i])

In your code, if you look at list1, you will find that it has been changed to ['h', 'h', 'h'] because that's what you told it to do (or at least as many h's as "some condition" will allow).

Answer from Kenny Ostrom on Stack Overflow
Discussions

Finding values in a string using for loops in Python 3 - Stack Overflow
I am writing a code that prompts the user to enter a sentence which is then defined as str1 and then is prompted to enter a word defined as str2. For example: Please enter a sentence: i like to More on stackoverflow.com
🌐 stackoverflow.com
In Python, can you find a substring using a for loop and equivalence (==) ? No regex - Stack Overflow
Here is my problem: Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack. I am More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
What is the most efficient way to find substrings in strings?
Easiest solution is to just use the 'in' operator like this: if "Leonardo DiCaprio" in article_title: return True And according to the top answer here it's also the fastest: whats-a-faster-operation-re-match-search-or-str-find Edit:cant get that return statement to indent for the life of me, you get the idea More on reddit.com
🌐 r/learnpython
22
4
January 11, 2022
Using while loops to find a character in a string
s = "abcdef" currIndex = 0 length = len(s) while currIndex < length: if s[currIndex] == 'e': print(currIndex) currIndex += 1 create an index variable (currIndex) set to the starting point of the string, 0. create a limit variable for your index (length), in this case the limit is the length of the string. set your while loop to execute as long as currIndex is less than the limit. keep in mind the length of the string will always be one higher than the last index..hense "<" instead of "<=". the first character is at index 0, and the last is at len(s)-1. each iteration of the while loop checks if the character of s at currIndex is equal to the char you're looking for and prints currIndex if it is. increment currIndex by 1 More on reddit.com
🌐 r/learnprogramming
6
1
December 20, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-all-occurrences-of-substring-in-string
Python - All occurrences of substring in string - GeeksforGeeks
July 12, 2025 - Extract start positions: A list ... match.start(). Using str.find() in a loop allows to find all occurrences of a substring by repeatedly searching for the next match starting from the last found index....
🌐
PythonForBeginners.com
pythonforbeginners.com › home › find all occurrences of a substring in a string in python
Find All Occurrences of a Substring in a String in Python - PythonForBeginners.com
July 8, 2022 - To find all occurrences of a substring in a string using the find() method in python, we will use the following steps. First, we will find the length of the input string and store it in the variable str_len. Next, we will find the length of the substring and store it in the variable sub_len.
🌐
CodeSignal
codesignal.com › learn › courses › practicing-string-operations-and-type-conversions-in-python › lessons › exploring-substring-search-in-python-strings
Exploring Substring Search in Python Strings
We're to identify all occurrences of each substring within its corresponding original string and return a list of the starting indices of these occurrences. Remember, index counting should start from 0. ... If we take the following lists: Original List: ["HelloWorld", "LearningPython", "GoForBroke", "BackToBasics"] Substring List: ["loW", "ear", "o", "Ba"].
🌐
Real Python
realpython.com › python-string-contains-substring
How to Check if a Python String Contains a Substring – Real Python
December 1, 2024 - Python counted how often the substring appears in the string and returned the answer. The text contains the substring four times. But what do these substrings look like? You can inspect all the substrings by splitting your text at default word borders and printing the words to your terminal using a for loop:
🌐
OpenStax
openstax.org › books › introduction-python-programming › pages › 8-3-searching-testing-strings
8.3 Searching/testing strings - Introduction to Python Programming | OpenStax
March 13, 2024 - Call the count() method to count the number of substrings in a given string. Search a string to find a substring using the find() method.
Find elsewhere
🌐
The Renegade Coder
therenegadecoder.com › code › how-to-check-if-a-string-contains-a-substring-in-python
How to Check if a String Contains a Substring in Python: In, Index, and More – The Renegade Coder
May 28, 2024 - Luckily, Python has an even cleaner syntax, and we’ll cover that today. To summarize, we can check if a string contains a substring using the in keyword. For example, "Hi" in "Hi, John" returns true. That said, there are several other ways to solve this problem including using methods like index() and find().
🌐
Initial Commit
initialcommit.com › blog › python-string-contains
Check If Python String Contains Substring - Initial Commit
April 8, 2021 - For each of the strings in job_titles, it successfully finds a match for the word "Python," even when it's in lowercase or misspelled. When you update your for loop this time, all the job postings are printed out: >>> for job in job_titles: ... if re.search(patterns, job): ... print(job) ... Python developer (Awesome Project) Django and python web engineer Senior Pyhton Developer · In this article, you saw how to determine whether or not a Python string contains a substring.
🌐
Vultr Docs
docs.vultr.com › python › standard-library › str › find
Python str find() - Locate Substring | Vultr Docs
December 25, 2024 - This example uses a loop to find all occurrences of "shells" in the string message. It collects the indices of each occurrence, demonstrating how to handle multiple findings. The find() function in Python provides a compelling way to locate substrings within strings, facilitating text processing and manipulation.
🌐
Medium
medium.com › @python-javascript-php-html-css › checking-for-substrings-in-python-alternatives-to-contains-and-indexof-250be759c912
Python Substring Checking: ‘contains’ and ‘indexOf’ Substitutes
August 24, 2024 - The function contains_substring_with_find checks if the substring is present in the main_string by returning True if the find method does not return -1. The find method searches for the substring and returns the lowest index where it is found, ...
🌐
CodeVsColor
codevscolor.com › python program to find a substring in a string - codevscolor
Python program to find a substring in a string - CodeVsColor
December 9, 2018 - We can use one loop and scan each character of the main string one by one. If any character is found equal to the first character of the substring, compare each subsequent character to check if this is the start point of the substring in the ...
🌐
PhoenixNAP
phoenixnap.com › home › kb › devops and development › how to substring a string in python
How to Substring a String in Python | phoenixNAP KB
November 27, 2025 - Note: To find the last occurring index, use the rindex and rfind methods. To find the indexes of all occurring substrings, use a for loop and check with the startswith string method.
🌐
Python Tutorial
pythontutorial.net › home › python string methods › python string find()
Python String find(): How to Find a Substring in a String Effectively
November 16, 2023 - The find() is a string method that finds a substring in a string and returns the index of the substring. The following illustrates the syntax of the find() method: str.find(sub[, start[, end]])Code language: CSS (css) ... start and end parameters are interpreted as in the slice str[start:end], ...
🌐
Programiz
programiz.com › python-programming › examples › substring-of-string
Python Program to Get a Substring of a String
# prints "love" print(my_string[2:6]) # prints "love python." print(my_string[2:]) # prints "I love python" print(my_string[:-1]) ... String slicing works similar to list slicing. The working of above code can be understood in the following points. [2:6] You need to specify the starting index and the ending index of the substring.
🌐
GeeksforGeeks
geeksforgeeks.org › check-if-string-contains-substring-in-python
Check if String Contains Substring in Python - GeeksforGeeks
July 20, 2024 - Check python substring in string using slicing. This implementation uses a loop to iterate through every possible starting index of the substring in the string, and then uses slicing to compare the current substring to the substring argument.
🌐
Analytics Vidhya
analyticsvidhya.com › home › a comprehensive guide to python string find() method
A Comprehensive Guide To Python String find() Method - Analytics Vidhya
May 19, 2025 - The find() method only returns the index of the first occurrence of the substring. If we want to find all occurrences of the substring, we can use a loop to iterate through the string and find each occurrence.
Top answer
1 of 1
2

Let's break down your code line by line:

needle = 'sses'
haystack = 'assesses'
count = 0                  # initialize the counter

Fine so far, this is only initialization.

index = haystack.index(needle) # get the first character in the substring

This line already is a problem, index raises a ValueError if it doesn't find the substring. Your program would crash in this case. You should instead use haystack.find(needle) which does the same, but instead of raising a ValueError it return -1 if the substring isn't found.

I do however not understand why you use this line at all. Your following loop will loop through the whole haystack and will also find the first appearance of needle.

string1 = haystack[index:len(needle) + index] # get the whole substring

This line is only valid if needle was found in the previous line. Also guess what string1 will be after this line? You are extracting the part of haystack where you previously found the substring needle. So the result will be string1 == needle, which won't help you in any way.

for position in range(0,len(haystack)): # loop through the string

ok, you loop through all positions in the string.

    if haystack[position:len(needle) + index] == string1: # match the 1st substring

So here I don't get why you want to find the first occurence again, which you already found before. Don't you want to check whether there is a match at position, no matter whether it is the first or second or third... one? So I would guess that haystack[position:len(needle) + index] is supposed to extract the substring of haystack that starts at position position and has length of needle. But why is there + index then? What has the first occurence (saved in index) to do with this? Don't you mean + position here? Finally you are comparing to string1 which as I said will be (if your code makes it to this line) equal to needle. So why not directly compare to needle?

    count += 1 # iterate the counter

This line is wrong indented in your posted code, it should be one deeper than the if-statement.

Finally you have to consider in your for-loop, that if position gets to the end of haystack there might not be a substring with length len(needle) starting at position anymore. So you probably want to stop iterating prior to that. (EDIT: I just notice that the code will run correctly anyway. It is not necessary to address this in python, because using indexes out of bounds of the string is allowed, but it would be in other languages.)

I guess this is an exercise, but if it wasn't there would be a much easier way to do this in python: count = haystack.count(needle). There is a small difference to your proposed algorithm though. string.count(substring) will return the number of non-overlapping matches, while your current code would find the number of non-overlapping and overlapping matches. The exercise as posted by you is unclear which of both is meant. But if you are supposed to find only non-overlapping results you need to consider this in your for-loop, too.

There are also several improvements one could make to the style and performance of your code, but I will not get into this, as you seem to have trouble getting it to work at all.

🌐
Reddit
reddit.com › r/learnpython › what is the most efficient way to find substrings in strings?
r/learnpython on Reddit: What is the most efficient way to find substrings in strings?
January 11, 2022 -

Hello,

There are several ways to find substrings in string, You could use substring in string you could use string.index(substring), or you could use string.find(substring) or even use regex.

I'm trying to understand if there is a significant difference between them for my use case, which is finding people names in article titles for example:

I want to check if Leonardo DiCaprio is in Leonardo DiCaprio gets called out for boarding superyacht: ‘eco-hypocrite’

What I usually do is:

def is_substring_in_string(substring: str, string: str):        
    #same thing as before but on the article title.
    string_alphanumeric = ''.join(e for e in string if e.isalnum()).lower()

    return substring in string_alphanumeric

def main():
    names = ["Harrison Ford","Leonardo DiCaprio","Eddie Murphy","Bruce Willis","Will Smith"]

    #removes unwanted charecters such as !@#$%^&*() etc and converts to lower case
    names_alnum_lower = [''.join(e for e in x if e.isalnum()).lower() for x in names]

    article_title = "Leonardo DiCaprio gets called out for boarding superyacht: eco-hypocrite"

    for idx, lower_name in enumerate(names_alnum_lower):
        if is_substring_in_string(lower_name,article_title):
            print(f"Actor Name: '{names[idx]}' is in article title '{article_title}'")

if __name__ == '__main__':
    main()

Imagine there are a bunch of articles and people's names. Is this method acceptable or will I be better off using regex or something else?