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

我试图删除字符串中元音的出现,除非它们是单词的开头.因此,例如像“男孩即将获胜”这样的输入应该输出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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值