Reverse an Integer in Python
12345 becomes 54321. Reverse the digits with a slice, then see the arithmetic version.
- Converting between int and str
- Reversing with [::-1]
- Keeping the sign of negative numbers
- 1
str(12345)"12345" - 2
[::-1]"54321" - 3
int(...)54321
Number → text → reversed → number
The problem
Reversing the digits of a number appears in palindrome-number checks, digit puzzles and interview questions. Numbers cannot be sliced, so the easiest way is to go through text and back.
Think of it like this
Reversing a number through text is like writing it on a strip of paper, turning the strip around, and reading it again. The digits come out in the opposite order, and you write the result down as a number again.
str(number)📜 Write the number on a strip[::-1]🔄 Turn the strip aroundint(...)🔢 Read it as a number againreversed_number📝 54321Reversing a number means writing its digits in the opposite order, so 12345 becomes 54321.
Key points
str(number)turns 12345 into the text"12345".[::-1]reverses the text into"54321".int(...)converts the reversed text back into a number.- Leading zeros disappear: reversing 1200 gives 21, because
int("0021")is 21.
When should you use it?
- Checking whether a number is a palindrome.
- Digit puzzles and interview questions.
- Practicing conversion between numbers and strings.
When not to use it
- Negative numbers:
int("54321-")fails, so reverseabs(number)and add the sign back. - When you must not use strings (some exercises): use
% 10and// 10in a loop instead.
Example code
number = 12345
# Reverse the digit text, then convert it back to an integer.
reversed_number = int(str(number)[::-1])
print(reversed_number)
Result of running the code
54321
Code explanation
str(number) turns the number into the text "12345", which can be sliced. The slice [::-1] reads that text from the last character to the first and produces "54321". int() converts it back into a number, which also removes any zeros that end up at the front.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Common mistakes
Reversing a negative number directly
The minus sign ends up at the end and int() fails.
int(str(-123)[::-1]) # ValueError
sign = -1 if number < 0 else 1
reversed_number = sign * int(str(abs(number))[::-1])
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Reverse a Number Reverse the decimal digits of a positive integer. Easy
- Palindrome Number Check whether a number reads the same backwards. Easy