[英]find first string starting with vowel in LIST Python
I am brand new to python -我是 python 的新手 -
I have to build a function called 'first__vowel'
.我必须构建一个名为
'first__vowel'
的函数。 ACCEPT a list of strings as input and RETURN the first string that starts with a lowercase vowel ("a","e","i","o", or "u")
.接受字符串列表作为输入并返回以小写元音
("a","e","i","o", or "u")
开头的第一个字符串。 if no string starts with vowel, RETURN the empty string ("")
.如果没有以元音开头的字符串,则返回空字符串
("")
。
Can you help build this function.你能帮助建立这个功能。
Thanks谢谢
Check this:检查这个:
vowels = ["a", "e", "i", "o", "u"]
def first_vowel(ss):
for s in ss:
if s and s[0] in vowels:
return s
return ""
Test:测试:
first_vowel(["Drere", "fdff", "", "aBD", "eDFF"])
'aBD'
You need:你需要:
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))
Or You can also use regex
或者您也可以使用
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)
You can always use str.startswith()
function too:您也可以随时使用
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.