Python How to Get the Last Digit of a Number (in 3 Steps)

To get the last digit of a number in Python:

  1. Access the string representation of the number.
  2. Get the last character of the string representation.
  3. Convert the character to an integer.

For example, let’s get the last digit of the number 162329:

n = 162329

# 1. Get the string representation
num_str = repr(n)

# 2. Access the last string of the digit string:
last_digit_str = num_str[-1]

# 3. Convert the last digit string to an integer:
last_digit = int(last_digit_str)

print(f"The last digit of {n} is {last_digit}")

Output:

The last digit of 162329 is 9

Shorthand Approach

You can also make the above code a bit shorter by combining steps 1-3 into a single expression:

n = 162329

last_digit = int(repr(n)[-1])

print(f"The last digit of {n} is {last_digit}")

The result:

The last digit of 162329 is 9

How to Get the Last Digit of a Decimal in Python

The same approach you learned earlier also works for decimal numbers.

To get the last digit of a decimal number, convert the number to a string, get the last character, and convert it back to an integer.

For example, let’s get the last decimal of a three-decimal approximation of Pi.

pi = 3.141
last_digit = int(repr(pi)[-1])

print(f"The last digit of {pi} is {last_digit}")

Output:

The last digit of 3.141 is 1

Further Reading

Python Tricks

How to Write to a File in Python

The with Statement in Python