[英]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.