开发者

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 i开发者_开发知识库sn't working. What's wrong?


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.


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


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)


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.


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.


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜