Skip to main content

How to Get the Last N Digits of a Number in Python

This guide explains how to extract the last N digits of a number in Python. We'll cover two main approaches: using the modulo operator (%) for integers, and string slicing for when you need to treat the number as a string (e.g., preserving leading zeros).

Getting the Last N Digits of an Integer Using the Modulo Operator (%)​

The modulo operator (%) is the most efficient way to get the last N digits of an integer. It returns the remainder of a division.

number = 24685
last_digit = number % 10 # Get the remainder when dividing by 10
print(last_digit) # Output: 5

number = 123456
last_two = number % 100 # Get last 2 digits
print(last_two) # Output: 56

last_three = number % 1000 # Get last 3 digits
print(last_three) # Output: 456
  • number % 10: Gets the remainder after dividing by 10, which is always the last digit.
  • number % 100: Gets the remainder after dividing by 100, which is always the last two digits.
  • number % 1000: Gets the remainder after dividing by 1000, which is always the last three digits, and so on.

Handling Negative Numbers​

To handle negative numbers correctly, use the abs() function to get the absolute value before applying the modulo operator:

number = -24685
last_digit = abs(number) % 10 # Get the absolute value first
print(last_digit) # Output: 5

number = -123456
last_two = abs(number) % 100 # Get the last 2 digits.
print(last_two) # Output: 56
  • The abs() function returns the absolute value of the number.

Getting the Last N Digits as a String Using Slicing​

If you need the last N digits as a string (for example, to preserve leading zeros that would be lost if converted to an integer), use string slicing:

number = 24685
last_two_str = str(number)[-2:] # Convert to string, then slice
print(last_two_str) # Output: '85' (as a string)

last_three_str = str(number)[-3:]
print(last_three_str) # Output: '685' (as a string)
  • str(number): Converts the number to a string.
  • [-2:]: This is a string slice. Negative indices count from the end of the string. [-2:] means "start at the second-to-last character and go to the end."
  • If the value is not a string to begin with, you have to cast it to string using str().