Getting TypeError:编写小程序时:“builtin\u function\u or\u method”对象不可下标

2024-04-26 07:04:42 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我只编写了很短的一段时间,正在尝试编写一个程序,计算一个句子中的元音,然后在我得到错误的那一刻将该数字返回给用户:

TypeError:'内置函数\或\方法'对象不可下标'

vowel = "aeiou"
vcount = 0
index = 0

sen = input("Enter sentence (If you enter nothing the program will terminate)\n")
senLen = len(sen)

while senLen > 0:
    sen = sen.lower
    while index < senLen:
        if "test"[index] in vowel:
            vcount = vcount + 1
            index = index + 1
    print("You latest sentance was", sen, "\nIt was", senLen, "Characters long\n", "And had", vcount, "Vowels")
    input("Enter sentence (If you enter nothing the program will terminate)\n")

提前谢谢


Tags: theyouinputindexifprogramwillsentence
1条回答
网友
1楼 · 发布于 2024-04-26 07:04:42

在这里:

sen = sen.lower

您没有将sen设置为原始字符串的小写版本,而是设置为完成此操作的string方法。要实际运行该方法并返回小写字符串,需要使用()调用它:

sen = sen.lower()

那么sen[index]将和你的实验"test"[index]一样有效。你知道吗

但是,您的程序仍然无法正常工作。一旦内部循环到达一个给定字符不是元音的点,它就会停止增加索引,因此它会永远检查同一个非元音字符。取消那条线。此外,您保存第一句话的长度,然后从不更新它。相反,每次用户输入一个句子时都要计算它。另外,您没有在循环中保存新的sen。最后,您永远不会重置indexvcount,因此该方面也不会处理新句子。你知道吗

vowel = "aeiou"

sen = input("Enter sentence (If you enter nothing the program will terminate)\n")
senLen = len(sen)

while senLen > 0:
    index = 0
    vcount = 0
    sen = sen.lower()
    while index < senLen:
        if sen[index] in vowel:
            vcount = vcount + 1
        index = index + 1
    print("Your latest sentence was", sen, "\nIt was", senLen, "Characters long\n", "And had", vcount, "Vowels")
    sen = input("Enter sentence (If you enter nothing the program will terminate)\n")
    senLen = len(sen)

通过使用break语句、sum()函数和多个print()调用,可以使代码更简短、更易于阅读:

vowel = "aeiou"

while 1:
    sen = input("Enter sentence (If you enter nothing the program will terminate)\n").lower()
    if not sen:
        break
    vcount = sum(c in vowel for c in sen)
    print("Your latest sentence was", sen)
    print("It was", len(sen), "characters long")
    print("And had", vcount, "vowels")

相关问题 更多 >