我试图删除字符串中元音的出现,除非它们是单词的开头.因此,例如像“男孩即将获胜”这样的输入应该输出Th.这是我迄今为止所拥有的.任何帮助,将不胜感激!
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)之前是非字母,这也意味着它们在一个词的开头.
重写为循环
def short(s):
new = ''
prior = ''
for c in s:
if not (c in 'aeiou' and prior.isalpha()):
new += c
prior = c
return new