加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 删除元音,除非它是单词的开头

发布时间:2020-12-20 11:40:33 所属栏目:Python 来源:网络整理
导读:我试图删除字符串中元音的出现,除非它们是单词的开头.因此,例如像“男孩即将获胜”这样的输入应该输出Th.这是我迄今为止所拥有的.任何帮助,将不胜感激! def short(s):vowels = ('a','e','i','o','u')noVowel= stoLower = s.lower()for i in toLower.split()
我试图删除字符串中元音的出现,除非它们是单词的开头.因此,例如像“男孩即将获胜”这样的输入应该输出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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读