Reputation: 127
I'm trying to find any vowels that comes first from the word. Output should be same with the output of the find() function.
So, for example,
from "python", output should be "4" ("python".find("o") is 4)
from "stock", output should be "2"
from "overflow", output should be "0"
from "styling", output should be "4" ("styling".find("i") is 4)
Actually What I am really trying to do is to remove vowel that comes first,
while 0 != 1:
if word[x] in 'aeiou':
word = word[x]+word[x+2:]
x = x+1
else: x = x+1
This is what I have been trying so far, but it causes "IndexError: string index out of range"
Upvotes: 0
Views: 3566
Reputation: 1
If you are just looking for the for the first appearance, you can use the .index() method for strings.
string = "Foo Bar"
vocals = {'a','e','i','o','u'}
def first_index(string, chars):
try:
return min(string.index(vocal) for vocal in chars if vocal in string)
except ValueError:
return -1
print(first_index(string, vocals))
Returns:
1
Upvotes: 0
Reputation: 22472
Here is a solution using a simple For loop which you might be familiar with and enumerate:
def position_of_first_vowel(word):
for index, char in enumerate(word):
if char in 'aeiou':
return index
return -1
for case in ["python","stock", "overflow", "styling", "zxc"]:
print("%s: %d" % (case, position_of_first_vowel(case)))
Output:
python: 4
stock: 2
overflow: 0
styling: 4
zxc: -1
N.B. The extra test case of zxc
is there to show the returning of -1
if a vowel does not occur in the word
Upvotes: 2
Reputation: 403128
This should be an easy one liner with next
and enumerate
.
def foo(string):
next((i for i, c in enumerate(string) if c in set('aeiou')), -1)
inputs = ["python", "stock", "overflow", "styling", "pythn"] # note the last string
print([foo(i) for i in inputs])
[4, 2, 0, 4, -1]
Upvotes: 2
Reputation: 2054
Here a solution using regex:
import re
VOWEL_REGEX = re.compile(r'[aeiou]')
def first_vowel_index(word):
match = VOWEL_REGEX.search(word)
if not match:
return -1
return match.start()
Tested for your examples:
>>> first_vowel_index('python')
4
>>> first_vowel_index('stock')
2
>>> first_vowel_index('overflow')
0
>>> first_vowel_index('styling')
4
Upvotes: 2