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 1777
别跟我提以往
别跟我提以往 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 try using regex:

    import re

    def disemvowel(text):
        return re.sub(r"G?[AEIOU]+G?", "", text, flags=re.IGNORECASE)
    
    
    tests = {"fragrance": "frrnc", "gargden": "rgdn", "gargdenag": "rgdn", "gag": ""}
    
    for test, value in tests.items():
        assert disemvowel(test) == value
    
    print("PASSED")
    

    Output:

    PASSED
    

提交回复
热议问题