我是python的新手-
我必须构建一个名为'first__vowel'
的函数。接受字符串列表作为输入
并返回以小写元音("a","e","i","o", or "u")
开头的第一个字符串。如果没有以元音开头的字符串,请返回空字符串("")
。
您能帮助构建此功能吗?
谢谢
答案 0 :(得分:2)
检查:
vowels = ["a", "e", "i", "o", "u"]
def first_vowel(ss):
for s in ss:
if s and s[0] in vowels:
return s
return ""
测试:
first_vowel(["Drere", "fdff", "", "aBD", "eDFF"])
'aBD'
答案 1 :(得分:0)
您需要:
def first_vowel(lst):
# iterate over list using for loop
for i in lst:
# check if first letter is vowel
if i and i[0] in ['a','e','i','o','u']:
return i
return ""
k = ['sad','dad','mad','asd','eas']
print(first_vowel(k))
或者您也可以使用regex
import re
def first_vow(lst):
pat = re.compile(r'^[aeiou][a-zA-Z]*')
for i in lst:
match = re.match(pat, lst)
if match:
return i
return ""
k = ['sad','Aad','mad','','asd','eas']
first_vow(k)
答案 2 :(得分:0)
您也可以随时使用str.startswith()
功能:
def first_vowel(lst):
for elem in lst:
if elem.startswith(('a','e','i','o','u')):
return elem
return ''
k = ['', 'b','sad','dad','mad','asd','eas']
print(first_vowel(k))
答案 3 :(得分:0)
l1 = ['hi', 'there', 'its', 'an' , 'answer', '']
def first_vowel(var):
for i in var:
if i.startswith(('a', 'e', 'i', 'o', 'u')): return i
first_vowel(l1) # output-> 'its'