jeudi 28 novembre 2019

How to detect vowels in a string and if a specific letter is beside a vowel, it is also considered a string?

Working on a function that would detect if there are any vowels in a given string, also checks if the letter "g" is beside the vowels or not. If the letter "g" is beside a vowel, then it will also be considered a vowel. I did post a question similar to this and got an answer that almost works but I got no explanation as to how it was done and no-one replied to my comment asking for clarification.

Here is the function:

    import re


def disemvowel(text):
    result = re.sub(r"G[AEIOU]+|[AEIOU]+G|[AEIOU]+", "", text, flags=re.IGNORECASE)
    print(result)


disemvowel("fragrance")
# frrnc

disemvowel('gargden')
# rgdn

disemvowel('gargdenag')
# rgdn

This function works for most cases except for when the letter 'g' both precedes and exceeds a vowel. For example, it does not work when I input 'gag' it returns 'g' when it isn't supposed to return anything. I just need clarification as to how this function works and what edits I could make to it to have it run properly for all scenarios.

This is my original function that I worked on but it only works for vowels since I could not figure out how to add a condition where it would detect the letter 'g' beside a vowel:

def disemvowel(text):
text = list(text)
new_letters = []
for i in text:
    if i.lower() == "a" or i.lower() == "e" or i.lower() == "i" or i.lower() == "o" or i.lower() == "u":
        pass
    else:
        new_letters.append(i)
print (''.join(new_letters))

disemvowel('fragrance')
# frgrnc

Aucun commentaire:

Enregistrer un commentaire