[英]Find the first occurence of a vowel in Python
I have a function isvowel
that returns either True
or False
, depending on whether a character ch
is a vowel. 我有一个函数
isvowel
返回True
或False
,具体取决于字符ch
是否是元音。
def isvowel(ch):
if "aeiou".count(ch) >= 1:
return True
else:
return False
I want to know how to use that to get the index of the first occurrence of any vowel in a string. 我想知道如何使用它来获取字符串中任何元音的第一次出现的索引。 I want to be able to take the characters before the first vowel and add them end of the string.
我希望能够在第一个元音之前取出字符并将它们添加到字符串的末尾。 Of course, I can't do
s.find(isvowel)
because isvowel
gives a boolean response. 当然,我不能做
s.find(isvowel)
因为isvowel
给出了一个布尔响应。 I need a way to look at each character, find the first vowel, and give the index of that vowel. 我需要一种方法来查看每个字符,找到第一个元音,并给出该元音的索引。
How should I go about doing this? 我该怎么做呢?
You can always try something like this: 你可以尝试这样的事情:
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)
Or, if you don't want to use regular expressions: 或者,如果您不想使用正则表达式:
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()
or for just the index (as asked): 或仅为索引(如所要求的):
(index for ch, index in itertools.izip(string, itertools.count()) if isvowel(ch)).next()
This will create an iterator and only return the first vowel element. 这将创建一个迭代器并仅返回第一个元音元素。 Warning: a string with no vowels will throw
StopIteration
, recommend handling that. 警告:没有元音的字符串会抛出
StopIteration
,建议处理它。
Here is my take: 这是我的看法:
>>> 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
Using next for a generator is quite efficient, it means you don't iterate though the entire string (once you have found a string). 对于生成器使用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.