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".
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.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With