Program to reverse words separated by set of delimiters in python

Sometimes we need to reverse words in a string while keeping delimiters in their original positions. This is useful when processing formatted text where the structure must be preserved but the word order needs to be reversed.

So, if the input is like s = "Computer/Network:Internet|tutorialspoint" with delimiters ["/", ":", "|"], then the output will be tutorialspoint/Internet:Network|Computer.

Algorithm

To solve this problem, we follow these steps ?

  • Extract all words (non-delimiter characters) and store them in a list
  • Iterate through the original string character by character
  • If the character is a delimiter, add it directly to the result
  • If we encounter a word group, pop the last word from our list (reverse order)

Using itertools.groupby()

The groupby() function groups consecutive characters based on whether they are delimiters or words ?

from itertools import groupby

class Solution:
    def solve(self, sentence, delimiters):
        words = []
        ans = ""
        
        # First pass: extract all words
        for k, g in groupby(sentence, lambda x: x in delimiters):
            if not k:  # if not delimiter (i.e., it's a word)
                words.append("".join(g))
        
        # Second pass: rebuild string with reversed words
        for k, g in groupby(sentence, lambda x: x in delimiters):
            if k:  # if delimiter
                ans += "".join(g)
            else:  # if word
                ans += words.pop()  # pop from end (reverse order)
                
        return ans

# Test the solution
ob = Solution()
s = "Computer/Network:Internet|tutorialspoint"
delims = ["/", ":", "|"]
result = ob.solve(s, delims)
print(result)
tutorialspoint/Internet:Network|Computer

Alternative Approach Using Regular Expressions

We can also solve this using regular expressions to split words and delimiters ?

import re

def reverse_words_with_delimiters(sentence, delimiters):
    # Create pattern to match delimiters
    pattern = '[' + re.escape(''.join(delimiters)) + ']'
    
    # Split into words and delimiters
    parts = re.split('(' + pattern + ')', sentence)
    
    # Extract words (non-empty, non-delimiter parts)
    words = [part for part in parts if part and part not in delimiters]
    
    # Reverse the words list
    words.reverse()
    
    # Rebuild string
    result = ""
    word_index = 0
    for part in parts:
        if part in delimiters:
            result += part
        elif part:  # non-empty word
            result += words[word_index]
            word_index += 1
    
    return result

# Test the solution
s = "Computer/Network:Internet|tutorialspoint"
delims = ["/", ":", "|"]
result = reverse_words_with_delimiters(s, delims)
print(result)
tutorialspoint/Internet:Network|Computer

How It Works

The groupby() approach works by:

  1. First pass: Groups consecutive characters and extracts words into a list
  2. Second pass: Rebuilds the string by keeping delimiters in place and popping words from the end of the list

Since pop() removes from the end of the list, we get words in reverse order while maintaining the delimiter positions.

Conclusion

Use itertools.groupby() for an elegant solution that preserves delimiter positions while reversing word order. The regular expression approach offers more control for complex delimiter patterns.

Updated on: 2026-03-25T12:49:38+05:30

440 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements