Python program to remove Nth occurrence of the given word

Created with Sketch.

Python Program to Remove Nth Occurrence of a Given Word

Introduction

In text processing and manipulation, there may be scenarios where you need to remove a specific occurrence of a word from a given text. This Python program demonstrates how to remove the Nth occurrence of a specified word from a string.

Understanding the Algorithm

The algorithm for removing the Nth occurrence of a word involves the following steps:

  1. Input Text: Accept the input text and the word to be removed.
  2. Count Occurrences: Iterate through the text, counting occurrences of the specified word.
  3. Remove Nth Occurrence: Identify the position of the Nth occurrence and remove it.
  4. Display Result: Print or display the modified text.

Python Program for Removing Nth Occurrence

def remove_nth_occurrence(text, word, n):
    # Split the text into words
    words = text.split()

    # Initialize variables to track occurrences and the resulting text
    occurrences = 0
    result_words = []

    # Iterate through the words and remove the Nth occurrence of the specified word
    for w in words:
        if w == word:
            occurrences += 1
            if occurrences == n:
                continue  # Skip the Nth occurrence
        result_words.append(w)

    # Reconstruct the modified text
    modified_text = ' '.join(result_words)

    return modified_text

# Example: Remove 2nd occurrence of the word "Python"
input_text_example = "Python is a popular programming language. Python code is readable and Python is versatile."
word_to_remove = "Python"
occurrence_to_remove = 2

# Perform removal
modified_text_example = remove_nth_occurrence(input_text_example, word_to_remove, occurrence_to_remove)

# Display the result
print(f"Modified Text: {modified_text_example}")

Output Example

Example: Remove 2nd Occurrence of the Word “Python”

Modified Text: Python is a popular programming language. code is readable and Python is versatile.

Explanation

The Python program defines a function remove_nth_occurrence that takes the input text, the word to be removed, and the Nth occurrence to remove. The function iterates through the words, skips the specified occurrence, and reconstructs the modified text.

The example provided demonstrates how to remove the 2nd occurrence of the word “Python” from a given text.

Conclusion

Text manipulation is a common task in programming, and the ability to remove specific occurrences of words can be valuable in various applications. This Python program provides a straightforward algorithm for removing the Nth occurrence of a specified word from a text string.

Feel free to experiment with different inputs to explore the program’s functionality. If you have any questions or need further clarification, please don’t hesitate to ask!

Leave a Reply

Your email address will not be published. Required fields are marked *