簡體   English   中英

TypeError: 'str' object is not callable 但我沒有覆蓋 str 方法?

[英]TypeError: 'str' object is not callable but I am not overwriting the str method?

我認為這與使用 input() 函數有關嗎? 我閱讀了其他建議它的答案,因為您正在嘗試重新定義 str 但正如您所看到的,我沒有在這里這樣做。 我知道有更好的方法來實現這個任務的目標,但我只是用它來探索 python 不是最佳的。

#Ask the user for a string and print out whether this string is a palindrome or not.
#(A palindrome is a string that reads the same forwards and backwards.)
repeat = True
while repeat == True:
    print(" enter a string " )
    input = str(input())


    #split string into an array of characters
    string = list(input)
    print(string)
    stringReverse = list(input[::-1])
    print(stringReverse)

    #loop an check if the first char matches last char up to the halfway
    length = len(string)
    #get the halfway point
    if length%2 == 0:
        #halfway point is even
        halfway = length/2
    else:
        halfway=(length+1)/2 #we are going to ignore this character



    print(halfway)

    print(stringReverse)
    #loop through each character in string
    currentpost = 0
    palindrome=True

    for index, letter in enumerate(string):
        #print(str(index)+ ' ' + letter)
        #print(stringReverse[index])
        print( letter +stringReverse[index])
        if letter == stringReverse[index]:
              print('match')
        else:
            print('break')
            palindrome = False



    print(palindrome)

    print("continue y/n")
    answer = str(input())
    print(answer)
    if answer =="n":
        repeat = False

錯誤信息如下

Traceback (most recent call last):
  File "/Users/nigel/Desktop/pythonshit/exercises6.py", line 48, in <module>
    answer = str(input())
TypeError: 'str' object is not callable

這是因為您在代碼的第二行命名了變量input 發生的情況是,由於input = str(input()) ,變量input變成了str ,並且當您稍后嘗試在answer = str(input())上調用它時,Python 認為您正在嘗試調用它字符串input

使用input = str(input())將字符串分配給變量input並隱藏函數input 然后當您調用input()它是一個字符串對象並且不可調用。

您的問題是scope變量陰影問題。

簡而言之:

當您嘗試answer = str(input()) python 認為input是您在那里定義的變量input = str(input())而您打算使用input()函數。

要解決您的問題:

input = str(input())更改為my_input = str(input())這樣您就不會遇到陰影問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM