'str'对象不能将字符串作为数组调用

时间:2013-08-18 09:43:45

标签: python string

我收到错误消息“TypeError:'str'对象不可调用”; 这是我的代码:

m=input()  
while(m!='0'):  
    c=0  
    for letter in range(len(m)):  
        if(m(letter) == '1'or '2'):  
            c++  
        if((m(letter) == '7'or'8'or'9') and (m(letter -1)=='2')):  
            c--  
        if(m(letter)=='0'):  
            c--  
    print(c)  
    m=input()  

这个错误是什么意思?

3 个答案:

答案 0 :(得分:3)

你有几个问题:

  1. Python使用方括号进行索引:m[letter]
  2. Python没有后增量运算符。您必须使用c += 1
  3. a == 'b' or 'c' or 'd'被解释为(a == 'b') or ('c') or ('d'),其始终为True。你想做a in ('b', 'c', 'd')

答案 1 :(得分:2)

错误在于您正在尝试调用字符串,而且它不可调用。看起来你想从字符串中的指定位置获取char。然后,使用m[letter]代替m(letter)

此外,您的if条件不正确,例如而不是if(m(letter) == '1'or '2'):,您应该使用in,如下所示:if m[letter] in ('1', '2')

此外,python中没有++--,而是使用+=1-=1

此外,whileif条件中存在一些冗余括号。

以下是改进的代码:

m = str(input())
while m != '0':
    c = 0
    for letter in range(len(m)):
        if m[letter] in ('1', '2'):
            c += 1
        if m[letter] in ('7', '8', '9') and m[letter - 1] == '2':
            c -= 1
        if m[letter] == '0':
            c -= 1
    print(c)
    m = str(input())

希望有所帮助。

答案 2 :(得分:1)

无论是字符串还是列表,索引都应该使用方括号来完成。所以使用

m[letter]

而不是m(letter). By using paranthesis, you are calling a function m`,它会抛出错误,因为m不是函数而只是一个字符串

相关问题