James
James

Reputation: 31

How do I match vowels?

I am having trouble with a small component of a bigger program I am in the works on. Basically I need to have a user input a word and I need to print the index of the first vowel.

word= raw_input("Enter word: ")
vowel= "aeiouAEIOU"

for index in word:
    if index == vowel:
        print index

However, this isn't working. What's wrong?

Upvotes: 3

Views: 7234

Answers (6)

Robert Lujo
Robert Lujo

Reputation: 16371

The same idea using list comprehension:

word = raw_input("Enter word: ")
res = [i for i,ch in enumerate(word) if ch.lower() in "aeiou"]
print(res[0] if res else None)

Upvotes: 2

Chinmay Kanchi
Chinmay Kanchi

Reputation: 65903

One alternative solution, and arguably a more elegant one, is to use the re library.

import re
word = raw_input('Enter a word:')
try: 
    print re.search('[aeiou]', word, re.I).start()
except AttributeError:
    print 'No vowels found in word'

In essence, the re library implements a regular expression matching engine. re.search() searches for the regular expression specified by the first string in the second one and returns the first match. [aeiou] means "match a or e or i or o or u" and re.I tells re.search() to make the search case-insensitive.

Upvotes: 1

Hugh Bothwell
Hugh Bothwell

Reputation: 56654

Just to be different:

import re

def findVowel(s):
    match = re.match('([^aeiou]*)', s, flags=re.I)
    if match:
        index = len(match.group(1))
        if index < len(s):
            return index
    return -1  # not found

Upvotes: 4

stonemetal
stonemetal

Reputation: 6208

index == vowel asks if the letter index is equal to the entire vowel list. What you want to know is if it is contained in the vowel list. See some of the other answers for how in works.

Upvotes: 1

yan
yan

Reputation: 20982

Try:

word = raw_input("Enter word: ")
vowels = "aeiouAEIOU"

for index,c in enumerate(word):
    if c in vowels:
        print index
        break

for .. in will iterate over actual characters in a string, not indexes. enumerate will return indexes as well as characters and make referring to both easier.

Upvotes: 5

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

for i in range(len(word)):
  if word[i] in vowel:
    print i
    break

will do what you want.

"for index in word" loops over the characters of word rather than the indices. (You can loop over the indices and characters together using the "enumerate" function; I'll let you look that up for yourself.)

Upvotes: 0

Related Questions