我试图去除字符串中元音的出现,除非它们是单词的开头。 因此,例如像"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 noVowelI am trying to remove the occurrences of the vowels in the string, except if they are the starting of a word. So for example an input like "The boy is about to win" should ouput Th by is abt t wn.Here is what I have so far. Any help would be appreciated!
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 newTry:
>>> 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'How it works:
The key part of the above if the generator:
c for i, c in enumerate(s) if not (c in 'aeiou' and i>1 and s[i-1].isalpha())The key part of the generator is the condition:
if not (c in 'aeiou' and i>1 and s[i-1].isalpha())This means that all letters in s are included unless they are vowels that are not either (a) at the beginning of s and hence at the beginning of a word, or (b) preceded by a non-letter which would also mean that they were at the beginning of a word.
Rewritten as for loop
def short(s): new = '' prior = '' for c in s: if not (c in 'aeiou' and prior.isalpha()): new += c prior = c return new更多推荐
发布评论