编写函数startWith元音(word),它接受一个单词作为参数,并返回一个以单词中第一个元音开头的子字符串。如果单词不包含元音,则函数返回“No元音”。在
示例
>>> startWithVowel('apple')
'apple'
>>> startWithVowel('google')
'oogle'
>>> startWithVowel('xyz')
'No vowel'
我的答案
^{pr2}$我的问题 我知道如何删除第一个元音字母,若单词包含任何元音,但我坚持这个代码。。使用此逻辑,它应该返回xyz的“no元音”。 但它返回'yz',我知道我错在哪里,这是第4行的逻辑问题。但我不知道怎么解决这个问题。在
下面是一个相当简单的方法:
这个怎么样-
如果要检查不区分大小写,请在上面的循环中使用
word[0].lower()
。在第4行中逻辑的问题是使用}。您要做的是比较word[0],它是一个字符,并将它与字符串}都不起作用。他们比较字符串,而不是迭代单词的每个字母并比较字符。您可以通过执行以下操作来解决此问题
!=
而不是{'aeiou'
进行比较。当然,单个字符永远不会等于字符串。除此之外,word[1:] in 'aeiou'
和{这意味着如果第一个字母是元音,则返回单词,否则,重复单词中的每个字母并查找元音。如果找到一个元音,则返回该索引中的单词,如果没有,则返回“无元音”
相关问题 更多 >
编程相关推荐