[英]Find the first occurence of a vowel in Python
我有一个函数isvowel
返回True
或False
,具体取决于字符ch
是否是元音。
def isvowel(ch):
if "aeiou".count(ch) >= 1:
return True
else:
return False
我想知道如何使用它来获取字符串中任何元音的第一次出现的索引。 我希望能够在第一个元音之前取出字符并将它们添加到字符串的末尾。 当然,我不能做s.find(isvowel)
因为isvowel
给出了一个布尔响应。 我需要一种方法来查看每个字符,找到第一个元音,并给出该元音的索引。
我该怎么做呢?
你可以尝试这样的事情:
import re
def first_vowel(s):
i = re.search("[aeiou]", s, re.IGNORECASE)
return -1 if i == None else i.start()
s = "hello world"
print first_vowel(s)
或者,如果您不想使用正则表达式:
def first_vowel(s):
for i in range(len(s)):
if isvowel(s[i].lower()):
return i
return -1
s = "hello world"
print first_vowel(s)
[isvowel(ch) for ch in string].index(True)
(ch for ch in string if isvowel(ch)).next()
或仅为索引(如所要求的):
(index for ch, index in itertools.izip(string, itertools.count()) if isvowel(ch)).next()
这将创建一个迭代器并仅返回第一个元音元素。 警告:没有元音的字符串会抛出StopIteration
,建议处理它。
这是我的看法:
>>> vowel_str = "aeiou"
>>> def isVowel(ch,string):
... if ch in vowel_str and ch in string:
... print string.index(ch)
... else:
... print "notfound"
...
>>> isVowel("a","hello")
not found
>>> isVowel("e","hello")
1
>>> isVowel("l","hello")
not found
>>> isVowel("o","hello")
4
对于生成器使用next非常有效,这意味着您不会遍历整个字符串(一旦找到了字符串)。
first_vowel(word):
"index of first vowel in word, if no vowels in word return None"
return next( (i for i, ch in enumerate(word) if is_vowel(ch), None)
is_vowel(ch):
return ch in 'aeiou'
my_string = 'Bla bla'
vowels = 'aeyuioa'
def find(my_string):
for i in range(len(my_string)):
if my_string[i].lower() in vowels:
return i
break
print(find(my_string))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.