Write a Python program to Find all occurrences in a given string ignoring the case

1. Introduction

This blog post will guide you through writing a Python program to find all occurrences of a specific substring in a given string, ignoring the case. This task is common in text processing and search operations and illustrates the use of string methods and basic Python programming concepts.

2. Program Steps

1. Define a function that takes two strings - the main string and the substring to find.

2. Convert both strings to the same case (lower or upper) to ignore case sensitivity.

3. Use a loop to find all occurrences of the substring in the main string.

4. Return or print the indices where the substring is found.

3. Code Program


def find_all_occurrences(main_string, search_string):
    # Step 2: Convert both strings to lowercase
    main_string_lower = main_string.lower()
    search_string_lower = search_string.lower()

    start = 0
    occurrences = []

    # Step 3: Loop to find all occurrences
    while True:
        index = main_string_lower.find(search_string_lower, start)

        # Break the loop if substring is not found
        if index == -1:
            break

        # Append the index to the list and move the start
        occurrences.append(index)
        start = index + 1

    # Step 4: Return the list of occurrences
    return occurrences

# Example usage
input_string = "Hello world, welcome to the world of Python."
substring = "world"
result = find_all_occurrences(input_string, substring)
print(f"Occurrences of '{substring}': {result}")

Output:

For the input string 'Hello world, welcome to the world of Python.' and substring 'world', the output will be:
Occurrences of 'world': [6, 26]

Explanation:

1. The function find_all_occurrences is designed to take two arguments: main_string and search_string.

2. Both main_string and search_string are converted to lowercase using .lower() to ensure the search is case-insensitive.

3. A while loop is used to find all occurrences of search_string_lower in main_string_lower. The find() method returns the lowest index of the substring (if found). If the substring is not found, find() returns -1.

4. Each found index is appended to the occurrences list. The search start index is updated to index + 1 to continue searching the string after the current found index.

5. Once all occurrences are found, the function returns the list occurrences.

This program demonstrates how to perform case-insensitive searches within strings in Python, a useful technique for many text processing applications.


Comments