我试图删除字符串中元音的出现,除非它们是单词的开头。因此,例如像 "The boy is about to win"
这样的输入应该输出 Th by is abt t wn
。这是我目前所拥有的。任何帮助,将不胜感激!
def short(s):
vowels = ('a', 'e', 'i', 'o', 'u')
noVowel= s
toLower = s.lower()
for i in toLower.split():
if i[0] not in vowels:
noVowel = noVowel.replace(i, '')
return noVowel
最佳答案
尝试:
>>> s = "The boy is about to win"
>>> ''.join(c for i, c in enumerate(s) if not (c in 'aeiou' and i>1 and s[i-1].isalpha()))
'Th by is abt t wn'
这个怎么运作:
上面如果生成器的关键部分:
c for i, c in enumerate(s) if not (c in 'aeiou' and i>1 and s[i-1].isalpha())
生成器的关键部分是条件:
if not (c in 'aeiou' and i>1 and s[i-1].isalpha())
这意味着
s
中的所有字母都包括在内,除非它们是元音,它们既不在 (a) s
的开头,也不是在单词的开头,或者 (b) 前面是非字母,这也意味着它们在一个词的开头。重写为
for
循环def short(s):
new = ''
prior = ''
for c in s:
if not (c in 'aeiou' and prior.isalpha()):
new += c
prior = c
return new
关于python - 删除元音,除非它是单词的开头,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28446136/