我在处理我正在开发的一个更大程序的一个小组件时遇到了麻烦。基本上我需要让用户输入一个单词,并且需要打印第一个元音的索引。
word= raw_input("Enter word: ")
vowel= "aeiouAEIOU"
for index in word:
if index == vowel:
print index
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用。怎么了?
尝试:
word = raw_input("Enter word: ")
vowels = "aeiouAEIOU"
for index,c in enumerate(word):
if c in vowels:
print index
break
Run Code Online (Sandbox Code Playgroud)
for .. in将迭代字符串中的实际字符,而不是索引。enumerate将返回索引和字符,并使引用两者变得更容易。