Removing all consonants from a string in Python
In this article, we will explore various ways in which we can remove all the consonants from a given string in Python.
The simplest way would be to convert a string to a list and replace the character with ‘0’ if it’s not a vowel and combine all the non-zero elements. Here we are converting the string to list to replace the element with zero because strings are immutable.
def removeCons(s): vowel="aeiouAEIOU" lis=[i for i in s] for i in range(len(s)): k=0 for j in range(len(vowel)): if(s[i]!=vowel[j]): k+=1 if(k==10): lis[i]=0 s="".join(i for i in lis if(i!=0)) return(s)
Another way to write the same code is below. Here instead to removing the consonants we added the vowels then joined to characters to form the string.
def removeCons(s): vowel="aeiouAEIOU" lis=[] for i in range(len(s)): k=0 for j in range(len(vowel)): if(s[i]==vowel[j]): k+=1 if(k!=0): lis.append(s[i]) s="".join(i for i in lis) return s
And the shortest code for the purpose looks like
def removeCons(s): lis=[] for x in s: if i in vowel: lis.append(i) s="".join(i for i in lis) return s
Input:
s="qwertyuioplkjhgfdsazxcvbnm" print(removeCons(s))
Output:
euioa
That’s it guys this was a simple tutorial to remove consonants from the string. If you could come up with more efficient code please do comment it.
Leave a Reply