I have a function isvowel
that returns either True
or False
, depending on whether a character ch
is a vowel.
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. 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.
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).
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.