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?

我怕爱的太早我们不能终老 提交于 2020-01-22 02:34:12

问题


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 given the string "fragrance" I want the string returned to say "frrnc"

This is what I have so far:

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

回答1:


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



回答2:


Interesting, does this stack?

So if you had the word baggga, would the outer g's turn into vowels, which then would turn the inner g also into a vowel? So is the output bg or is it b?

You can either remove all g's next to vowels and then in a second step remove all vowels.

Or you could replace all g's next to vowels by, let's say 'a', and then remove all vowels. If the 'g is a vowel'-rule stacks, you may have to repeat the first step until the string does not change anymore.




回答3:


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


来源:https://stackoverflow.com/questions/59013967/how-to-disemvowel-a-string-with-a-condition-where-if-the-letter-g-is-right-bes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!