Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing "y" immediately before or after any vowel in a string in python

I want to remove vowels in a string, for simplicity I have only included small letters in below code

for x in "aeiou":
  st = st.replace(i,"")
  return st

this is working fine, however i am wondering how to approach the scenario where I want to also remove y in a string including vowels if it has any vowel to the left or right e.g after running the function on "may" it should return "m", similarly "mystery" to "mystry".

like image 586
N997 Avatar asked Feb 23 '19 03:02

N997


People also ask

How do I remove a character from the beginning and end of a string in Python?

Use the . strip() method to remove whitespace and characters from the beginning and the end of a string. Use the . lstrip() method to remove whitespace and characters only from the beginning of a string.

How do you remove a repeated vowel from a string?

Approach: Iterate string using a loop and check for the repetitiveness of vowels in a given sentence and in case if consecutive vowels are found then delete the vowel till coming next consonant and printing the updated string.

How do you strip the alphabet of a string in Python?

Python Remove Character from String using replace() We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.


1 Answers

This is probably a homework assignment, but really the simplest (although not necessarily the fastest one) would be using regex:

import re
p = re.compile(r'(?i)y?[aeiou]y?')

p.sub('', 'may')
# 'm'

p.sub('', 'mystery')
# 'mystry'

Using pure python, you can listify your string, iterate over each character, remove characters accordingly (yes, you have done this, so you will need to modify your existing code using if statements to account for the case of "y"), and rejoin back. Here's an example.

def remove_vowels_with_y(string):
    # Cache vowel set for better lookup performance.
    v = set('aeiouAEIOU')
    # Listify your string. This is because strings are immutable.
    chars = list(string) + [''] # Sentinel character.
    # Initialization.
    filtered = []
    prev_is_vowel = False
    for i, c in enumerate(chars[:-1]): 
        # Add elements to `filtered` if conditions are met.
        if not (c in v or (c in 'yY' and (prev_is_vowel or chars[i+1] in v))):
            filtered.append(c)
        prev_is_vowel = c in v

    # Join filtered list and return result.    
    return ''.join(filtered)

remove_vowels_with_y('may')
# 'm'

remove_vowels_with_y('mystery')
# 'mystry'
like image 143
cs95 Avatar answered Nov 03 '22 17:11

cs95