如果第一个字母是元音,如何删除它,如果有n,则不返回元音

2024-10-03 11:15:16 发布

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

编写函数startWith元音(word),它接受一个单词作为参数,并返回一个以单词中第一个元音开头的子字符串。如果单词不包含元音,则函数返回“No元音”。在

示例

>>> startWithVowel('apple')
'apple'
>>> startWithVowel('google')
'oogle'
>>> startWithVowel('xyz')
'No vowel'

我的答案

^{pr2}$

我的问题 我知道如何删除第一个元音字母,若单词包含任何元音,但我坚持这个代码。。使用此逻辑,它应该返回xyz的“no元音”。 但它返回'yz',我知道我错在哪里,这是第4行的逻辑问题。但我不知道怎么解决这个问题。在


Tags: 函数no字符串示例apple参数google逻辑
3条回答

下面是一个相当简单的方法:

def startWithVowel(word):
    for i, c in enumerate(word):
        if c.lower() in 'aeiou':
            return word[i:]
    return 'No vowel'

>>> for word in 'apple', 'google', 'xyz', 'BOGGLE':
...     print startWithVowel(word)
apple
oogle
No vowel
OGGLE

这个怎么样-

>>> def startWithVowel(word):
...     while len(word) > 0 and word[0] not in 'aeiou':
...             word = word[1:]
...     if len(word) == 0:
...             return 'No vowel'
...     return word
...
>>> startWithVowel('apple')
'apple'
>>> startWithVowel('google')
'oogle'
>>> startWithVowel('xyz')
'No vowel'
>>> startWithVowel('flight')
'ight'

如果要检查不区分大小写,请在上面的循环中使用word[0].lower()。在

第4行中逻辑的问题是使用!=而不是{}。您要做的是比较word[0],它是一个字符,并将它与字符串'aeiou'进行比较。当然,单个字符永远不会等于字符串。除此之外,word[1:] in 'aeiou'和{}都不起作用。他们比较字符串,而不是迭代单词的每个字母并比较字符。您可以通过执行以下操作来解决此问题

def startWithVowel(word):
    if word[0] in 'aeiou':
        return word
    else:
        for i in range(1, len(word)):
            if word[i] in 'aeiou': return word[i:]
        return "No vowel"

这意味着如果第一个字母是元音,则返回单词,否则,重复单词中的每个字母并查找元音。如果找到一个元音,则返回该索引中的单词,如果没有,则返回“无元音”

相关问题 更多 >