简体   繁体   中英

Python code not working: TypeError,'int' object is not callable

The following Python code gives out error :

TypeError: 'int' object is not callable.

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. To solve it, just shift it by one with a simple -1 operation.

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM