简体   繁体   中英

Reversing a number using list in python

I want to reverse a number but I get this error:

"TypeError: 'type' object is not subscriptable"

I would be grateful if you could correct my code.here is my code:

number=input("enter your number ")
num=int(number)
count=0
list1=[]
while(num!=0):
    list1.append(num%10)
    num=num//10
    count=count+1
print(list1[::-1])
k=len(list1)
after=0
for h in range(k):
    after+=int(list[h])*(10**h)
    h=-1
print(after)

You can do it easily using list's (create, reverse, join):

''.join(map(str, list(reversed(list(str(num))))))

or just, much easier:

int(str(num)[::-1])

You have to cast your int into a str , reverse the string and cast it back.

This is how I'd go about it:

number = input("enter your number ")
number = int(str(number)[::-1])

You have to use list1 in line 13.

Also, I am not sure what you want to do, you algorithm doesn't seem to be right and code is not pythonic at all.

Read about map function. If you want to do using list. (Don't use the typically C++ while loop) To break a number into list of single digits use:

list1 = map(int,str(num)) 

can do this as well

return eval(str(number)[::-1])

read more about extended slice methods to know more

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