为了账号安全,请及时绑定邮箱和手机立即绑定

一一检测一个字符是否有特定字母,然后计算它们的数量

一一检测一个字符是否有特定字母,然后计算它们的数量

蛊毒传说 2021-09-28 16:18:29
我正在尝试制作一个程序来检测您键入的单词中有多少个元音。这是我的源代码(我有多个代码):a = input("word - ").lower()for i in range(1, len(a)+1):  if a[str(i)] == "a" or "e" or "i" or "o" or "u":    print("ok")else:  print("no")`我得到错误:TypeError: string indices must be integers第二个:a = input("word - ").lower()for letter in a:  if letter == "a" or "e" or "i" or "o" or "u":    value = 0    value = value + 1print(value)还给我一个错误:TypeError: string indices must be integers第三个稍微复杂一点:a = input("rec - ").lower()for i in range(1, len(a)+1):  if a[str(i)] == "a":    print("yes a")  elif a[str(i)] == "e":    print("yes e")  elif a[str(i)] == "i":    print("yes i")  elif a[str(i)] == "o":    print("yes o")  elif a[str(i)] == "u":    print("yes u")我正在Repl.it上使用 Python 3.6.1您可以在我的个人资料中查看完整的源代码。我感谢您的帮助。谢谢!
查看完整描述

3 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

在第一个和最后一个示例中,您使用字符串作为索引 (a[str(i)])。但是,indeces 始终是整数。请记住,第一个索引始终为 0,而不是 1。您的 for 循环从 1 开始迭代。由于第一个元素的索引为 0,因此最后一个元素的索引为 len(array) - 1,这意味着您的 for-循环应该只迭代到 len(a)。for 循环索引的问题也适用于最后一个示例。

在第二个示例中,您没有正确使用 or 语句。你不能这样比较他们。你必须这样写:

if letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u":

为了缩短这个,只需写:

if letter in "aeiou":

在这里,您检查字母是否在字符串“aeiou”中。

在您的第二个示例中,每次找到元音时,您还将值重置为零。这将导致值仅为 1 或未定义。将 value = 0 放在 for 循环之前,它应该可以工作。


查看完整回答
反对 回复 2021-09-28
?
潇湘沐

TA贡献1816条经验 获得超6个赞

您曾经a[str(i)]访问字符串中的字母,其中 str(i) 是一个字符串并且所有数组索引都必须是整数,这就是错误的原因。

i 已经是一个整数,所以你应该使用 a[i] 来访问字母。

也正如@usr2564301 所说,你的or陈述是错误的

if letter == "a" or "e" or "i" or "o" or "u":

应该,

if letter in ["a", "e", "i", "o", "u"]:


查看完整回答
反对 回复 2021-09-28
?
PIPIONE

TA贡献1829条经验 获得超9个赞

请注意,在索引数组或字符串时需要使用整数:


a = input("word - ").lower()

for i in range(len(a)):

    if a[i] == "a" or "e" or "i" or "o" or "u":

        print("ok")

else:

    print("no")

这应该可以解决您的问题:


vowels = set("aeiou")

user_input = input("word - ").lower()

vowels_count = len([letter for letter in user_input if letter in vowels])


print(f"you typed {vowels_count} vowel(s)")


查看完整回答
反对 回复 2021-09-28
  • 3 回答
  • 0 关注
  • 164 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信