【问题标题】:To count the number of vowels in the string(python)计算字符串中元音的数量(python)
【发布时间】:2017-10-04 07:31:33
【问题描述】:

这是我的代码:

word='azcbobobegghakl'

cout=0

for leter in range(word):

    if leter=='a' or leter=='e' or leter=='i' or leter=='o' or leter=='u':  

        cout += 1

print('Number of vowels: '+ str(cout))

我遇到了错误:

TypeError: 'str' 对象不能被解释为整数

【问题讨论】:

  • 非常接近...for leter in word 很好 - 不需要range...。
  • 谢谢!那行得通。但我认为该范围会从“单词”中获取单个字母并检查它的条件还是我弄错了?

标签: python-3.x


【解决方案1】:

您选择了范围(字)中的字母[原文]而不是for leter[sic] in word

在你的 python 控制台中试试这个:

>>> range("word")
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer

这是您遇到的错误。

这应该可以修复您的代码:

word='azcbobobegghakl'

cout=0

for leter in word:

    if leter=='a' or leter=='e' or leter=='i' or leter=='o' or leter=='u':  

        cout += 1

print('Number of vowels: '+ str(cout))

【讨论】:

    【解决方案2】:

    您已经有了固定版本,但至于解释。您正在使用范围(单词)。 Word 是一个字符串,而 range 需要一个数字。如果你需要一个单词的长度,你可以使用 len()。

    【讨论】:

      【解决方案3】:

      让我告诉你 range 是一个函数,它为你提供 integer 的值列表,即 range(10) 将给我 0,1,2,3,4,5, 6,7,8,9。 这仅适用于数字。 你可以把它改成 for letter in word:

      `for letter in range(len(word)):`
      
      
      
      
      
        `if word[leter]=='a' or word[leter]=='e' or word[leter]=='i' or` word[leter]=='o' or word[leter]=='u':  
      
      
      
      
      
      cout += 1
      

      这是因为 len(word) 给了我长度和范围,给了我一个从 0 迭代到 len-1 的迭代器 现在我可以使用索引来访问每个字母 这是我的代码:

       word='azcbobobegghakl'
      
      cout=0
      
      for leter in word:
      
      
      
      if leter=='a' or leter=='e' or leter=='i' or leter=='o' or leter=='u': 
      
      
      
      
      
       cout += 1
      
      print('Number of vowels: '+ str(cout))
      

      word='azcbobobegghakl'
      
      cout=0
      
      for leter in range(len(word)):
      
      
      
      if word[leter]=='a' or word[leter]=='e' or word[leter]=='i' or word[leter]=='o' or word[leter]=='u':  
      cout += 1
      
      print('Number of vowels: '+ str(cout))
      

      【讨论】:

        猜你喜欢
        • 2011-09-05
        • 2013-11-26
        • 1970-01-01
        • 2021-06-09
        • 2020-02-19
        • 2020-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多