Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Examples
  3. Reverse a Number

Number Programs · Python example

Reverse a Number

Reverse the digits of an integer by converting it to a string.

Open the compilerAll examples
beginnerstringsintegersslicing

Strings support slicing with a step. A step of -1 walks backwards through the characters, which reverses the digits.

example.py
number = 1200
reversed_text = str(number)[::-1]
reversed_number = int(reversed_text)

print(f"Original: {number}")
print(f"Reversed: {reversed_number}")

How the code works

  • 1200 becomes the string '1200'.
  • Slicing produces '0021'.
  • Converting to int yields 21.

Key ideas

  • str(number) converts the integer to text.
  • [::-1] takes every character from the end to the start.
  • int() removes leading zeros when converting back to a number.

Try changing it

  • Reverse a number without converting it to a string.
  • Handle negative numbers by preserving the sign.
  • Check whether a number is a palindrome.

Related examples

beginner

Palindrome Checker

Normalize a phrase and compare it with its reverse to detect a palindrome.

beginner

Sum of Natural Numbers

Add the first n natural numbers with a loop and compare the closed formula.

Previous examplePrime Number CheckerNext exampleSum of Natural Numbers

Expected output

Original: 1200
Reversed: 21

Output is compared after trimming trailing whitespace on each line. Run the code to see it produced by CPython in your browser.

Practice next

Apply the same idea with automatic tests or browse a guided project.

ExercisesProjects