数一数字符串中第一个元音之前的辅音

2024-10-02 00:35:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个简单的猪拉丁语翻译。以下是我目前所掌握的情况:

while True:
  phrase = input('Translate > ').lower().split()

  for word in phrase:
    if word[0] in 'aeiou': # If the first letter is a vowel
      print(word + '-way') # Add suffix 'way'
    else:
      c = # Number of consonants before the first vowel
      print (word[c:] + word[0:c] + '-ay')

如何使c尽可能简单地等于word中第一个元音之前的辅音数目?我不想使用函数。在

我不想定义我的函数。很抱歉。在


Tags: the函数intrueinput情况lowerway
1条回答
网友
1楼 · 发布于 2024-10-02 00:35:32

使用itertools.takewhile

 from itertools import takewhile

 c = len(list(takewhile(lambda x: x not in "aeiou", word)))

takewhile得到一个predicate,这就是这里的lambda,当谓词是True时,它将使用元素,因此在这种情况下,只要遇到一个元音,该方法就会停止并返回到该点为止的辅音列表,我们只需使用len函数来检查列表中有多少辅音,为我们提供c的索引。在

相关问题 更多 >

    热门问题