[英]find first string starting with vowel in LIST Python
我是 python 的新手 -
我必須構建一個名為'first__vowel'
的函數。 接受字符串列表作為輸入並返回以小寫元音("a","e","i","o", or "u")
開頭的第一個字符串。 如果沒有以元音開頭的字符串,則返回空字符串("")
。
你能幫助建立這個功能。
謝謝
檢查這個:
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'
你需要:
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)
您也可以隨時使用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))
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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.