[英]Python code not working: TypeError,'int' object is not callable
The following Python code gives out error :以下 Python 代码给出错误:
TypeError: 'int' object is not callable.类型错误:“int”对象不可调用。
Can anyone help me out?谁能帮我吗?
string = "This is a string, but I want to print it backwards"
stringLen = len(string)
newString = []
while stringLen >= 0:
newString.append(string[stringLen])
stringLen = stringLen - 1
result = ''.join(newString)
print(result)
No able to reproduce the error.无法重现错误。 However, you have an但是,您有一个
Index out of range error.索引超出范围错误。
This is because the indentation starts at 0. So string[stringLen]
is out of bound at the first iteration.这是因为缩进从 0 开始。所以string[stringLen]
在第一次迭代时超出了界限。 To solve it, just shift it by one with a simple -1
operation.要解决它,只需使用简单的-1
操作将其移一位即可。
Also, because we are now going in backward direction, we should stop when the counter is strictly superior to 0. If you go up to 0
, you will print the first character (so restarting iterating).此外,因为我们现在是向后移动,所以当计数器严格大于 0 时,我们应该停止。如果上升到0
,您将打印第一个字符(因此重新开始迭代)。
Here the code:这里的代码:
string = "This is a string, but I want to print it backwards"
stringLen = len(string)
newString = []
while stringLen > 0:
# Here string is shifted by 1
newString.append(string[stringLen-1])
stringLen = stringLen - 1
result = ''.join(newString)
print(result)
# sdrawkcab ti tnirp ot tnaw I tub ,gnirts a si sihT
You can check your output by just calling:您只需调用以下命令即可检查输出:
print(string[::-1])
# sdrawkcab ekil skool txet siht woh rednow I
Some explanations here 这里有一些解释
Hope that helps !希望有帮助!
you can get the same result with this code :您可以使用此代码获得相同的结果:
string = "This is a string, but I want to print it backwards"
result=''.join(string[::-1])
print(result)
outbut:出处:
sdrawkcab ti tnirp ot tnaw I tub ,gnirts a si sihT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.