对于Python,我是初学者,对以下内容不是很了解:
我尝试打印字符串中所有元音的索引:
string = "And now for something completely different"
vowel = "aeiouAEIOU"
for i in range(0, len(string)):
if i in vowel:
print(string[i])
所以,我认为输出应该是这样的:
[0, 5, 9, 13, 15, 18, 23, 27, 29, 34, 37, 39]
然后我得到这个错误:
"'in <string>' requires string as left operand, not int"
我想我确实明白我尝试比较的两个变量都应该是字符串,但我不明白“i”为什么不是字符串,因为它确实由“字符串”的每个字母组成。
如何摆脱这个错误?也许我做错了更多,这就是这段代码不起作用的原因。
我试图查看类似的问题,但答案并不完全符合我的问题,因此我仍然没有弄明白。
最佳答案
but I do not see how 'i' is not a string because it does go by every letter of 'string'.
不是,这里的i
是一个整数,范围是0到len(string) - 1
。您可以通过在循环中 print
ing i
看到它...
如果要遍历string
字母,则拼写为:
for char in string:
print char
现在你需要索引(用于输出)和字母(用于查找),所以你应该使用 enumerate(sequence)
产生 (index, item)
sequence
中每个项目的元组:
for index, char in enumerate(string):
if char in vowel:
print index
您还可以通过将 vowels
设为 set
来加快查找速度:
vowels = set("aeiouAEIOU")
这不会更改其余代码,但查找的时间复杂度为 O(1) 而不是 O(N)
关于python - 元音索引 : Python error "' in <string >' requires string as left operand, not int",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46487616/