How to disemvowel a string with a condition where if the letter “g” is right beside a vowel, it would also be considered a vowel?

前端 未结 3 1775
别跟我提以往
别跟我提以往 2021-01-27 17:29

Working on a homework question where all the vowels in a string need to be removed and if the letter \"g\" is beside a vowel, it would also be considered a vowel. For example gi

3条回答
  •  醉话见心
    2021-01-27 18:15

    You can add a variable to track if the previous letter was a vowel.

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

    Input

    disemvowel('fragrance')

    Output

    frrnc
    

    Input

    disemvowel('gargden')
    

    Output

    grgdn
    

提交回复
热议问题