Skip to content Skip to sidebar Skip to footer

Remove Vowels Except If It The Starting Of The Word

I am trying to remove the occurrences of the vowels in the string, except if they are the starting of a word. So for example an input like 'The boy is about to win' should ouput

Solution 1:

One approach is to use a regular expression that replaces vowels not preceded by a word boundary. Also, you might want to think about some more interesting test cases if your code is supposed to handle arbitrary text with various types of punctuation.

import re
s = "The boy is about to win (or draw). Give him a trophy to boost his self-esteem."
rgx = re.compile(r'\B[aeiou]', re.IGNORECASE)
print rgx.sub('', s)  # Th by is abt t wn (or drw). Gv hm a trphy t bst hs slf-estm.

Solution 2:

Try:

>>>s = "The boy is about to win">>>''.join(c for i, c inenumerate(s) ifnot (c in'aeiou'and i>1and s[i-1].isalpha()))
'Th by is abt t wn'

How it works:

The key part of the above if the generator:

c for i, c in enumerate(s)ifnot(c in 'aeiou' and i>1 and s[i-1].isalpha())

The key part of the generator is the condition:

ifnot(c in 'aeiou' and i>1 and s[i-1].isalpha())

This means that all letters in s are included unless they are vowels that are not either (a) at the beginning of s and hence at the beginning of a word, or (b) preceded by a non-letter which would also mean that they were at the beginning of a word.

Rewritten as for loop

def short(s):
    new = ''
    prior = ''for c in s:
        ifnot(c in 'aeiou' and prior.isalpha()):
            new += cprior= c
    returnnew

Solution 3:

You can use regex on the rest of the string (ignoring the first character):

import re
s = 'The boy is about to win'
s = s[0] + re.sub(r'[aeiou]', '', s[1:])
print s # Th by s bt t wn

Solution 4:

Use a regular expression:

import re

re.sub("(?<!\b)[aeiouAEIOU]", '', s)

Solution 5:

>>> re.sub('(?<=\w)[aeiou]','',"The boy is about to win")
'Th by is abt t wn'

Post a Comment for "Remove Vowels Except If It The Starting Of The Word"