Skip to content
Related Articles
Open in App
Not now

Related Articles

Python Program to Reverse consonants in a given string without affecting the other elements

Improve Article
Save Article
Like Article
  • Last Updated : 10 Jan, 2023
Improve Article
Save Article
Like Article

Given a string, the task is to write a Python program to reverse only the consonants of a string without affecting the other elements’ positions.


Input : hello

Output : lelho

Explanation: h,l,l are consonants in the given string. After modifying the string their occurrences are l,l,h and vowels positions are not changed.


  • Convert the string into a list of characters.
  • Maintain another Python list for storing consonants.
  • If the current element is consonant then append the current element to the consonant list.
  • Start traversing the list again and replace the consonants with the element present in the consonant list from last.
  • Finally, convert the list into a string and return it.


Below is the implementation of the above approach.


# Function to check element is consonant or not
def isConsonant(i):
    vow = ['a', 'e', 'i', 'o', 'u']
    # if not vowel return true
    if i not in vow:
        return True
    return False
def reverseConsonant(s):
    # convert string into list
    s = list(s)
    # storing consonants in a list
    cons = []
    for i in s:
        if isConsonant(i):
    k = len(cons)-1
    # Replace the consonants with the
    # element present in consonant list
    # from last.
    for i in range(len(s)):
        if isConsonant(s[i]):
            s[i] = cons[k]
            k -= 1
    return "".join(s)
print(reverseConsonant("hello world"))


delrow ollh

Complexity Analysis

Time complexity: O(n)

Space Complexity: O(n) for storing consonants

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!