除非单词开始,否则删除元音(Remove vowels except if it the starting of the word)

编程入门 行业动态 更新时间:2024-10-22 05:17:11
除非单词开始,否则删除元音(Remove vowels except if it the starting of the word)

我试图去除字符串中元音的出现,除非它们是单词的开头。 因此,例如像"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

I 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 new

Try:

>>> 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

更多推荐

本文发布于:2023-07-06 08:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047635.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元音   单词   Remove   word   starting

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!