Now I am looking for the best way to reverse the digits in an integer. For instance x = 12345 should become y = 54321.

When I first looked at this problem, I thought it would be very simple routine stuff. To my surprise this thing is loaded with programming possibilities.

# reverse integer digit by digit, the long way ...
x = 12345
x_string = str(x)                           # "12345"
x_list = list(x_string)                     # ['1', '2', '3', '4', '5']
# uses reversed on the list
x_reversedlist = reversed(x_list)           # ['5', '4', '3', '2', '1']
x_reversedstring = "".join(x_reversedlist)  # "54321"
x_reversed = int(x_reversedstring)          # 54321
print x_reversed

Why use the list as a middleman when you can call reversed() on the string?

# reverse integer digit by digit, slightly modified ...
x = 12345
x_string = str(x)                           # "12345"
# uses reversed() directly on the string
x_reversedobject = reversed(x_string)       # <reversed object at 0x009D2D70>
x_reversedlist = list(x_reversedobject)     # ['5', '4', '3', '2', '1']
x_reversedstring = "".join(x_reversedlist)  # "54321"
x_reversed = int(x_reversedstring)          # 54321
print x_reversed

That looks like the setup for a one-liner:

# reverse integer digit by digit, as a one liner ...
x = 12345
x_reversed = int("".join(list(reversed(str(x)))))
print "%d reversed --> %d" % (x, x_reversed)  # 12345 reversed --> 54321

String slicing should cut that really short:

# reverse integer digit by digit, simpler with slicing ...
x = 12345
x_reversed = int(str(x)[::-1])
print "%d reversed --> %d" % (x, x_reversed)  # 12345 reversed --> 54321

Thank you! I am still trying to digest the one liners, particularly:

x_reversed = int(str(x)[::-1])

Can anybody break that down for me so I can see the flow?

Thank you! I am still trying to digest the one liners, particularly:

x_reversed = int(str(x)[::-1])

Can anybody break that down for me so I can see the flow?

x = 12345
x_string = str(x)                   # "12345"
x_reversedstring = x_string[::-1]   # "54321"
x_reversed = int(x_reversedstring)  # 54321

You need to fill in the defaults to get a better feeling for slicing:

str1 = "madam"
begin = 0        # default is 0
end = len(str1)  # end is exclusive, default is length of string
step = -1  # - sign --> from the end in steps of 1, default is 1
reversed_string = str1[begin:end:step]
int(str(x)[::-1])

What the ... I never knew you could do that!!!

LOL!

Jeff

Testing results:

>>> s = "my test string"
>>> s[::-1]
'gnirts tset ym'
>>> s[::2]
'm etsrn'
>>> s[::-2]
'git sty'
>>>

:cool:

This question has already been answered. Start a new discussion instead.