Remove the last Digit from an Integer in Python

avatar

Borislav Hadzhiev

Last updated: Jul 8, 2022

banner

Check out my new book

Remove the last Digit from an Integer in Python #

To remove the last digit from an integer, use floor division to divide the integer by 10, e.g. result_1 = my_int // 10. Floor dividing by 10 will strip the last digit from the integer.

main.py
my_int = 1357 result_1 = my_int // 10 print(result_1) # 👉️ 135 # ------------------------------------------ result_2 = int(str(my_int)[:-1]) print(result_2) # 👉️ 135

The first example floor-divides the integer by 10 to remove the last digit.

Division / of integers yields a float, while floor division // of integers result in an integer.

The result of using the floor division operator is that of a mathematical division with the floor() function applied to the result.

Note that Python integers are immutable, so the only way to remove a digit from an integer is to create a new integer that doesn't contain the digit.

An alternative approach is to use string slicing.

To remove the last digit from an integer:

  1. Use the str() class to convert the integer to a string.
  2. Use string slicing to get a slice of the string up to the last digit.
  3. Use the int() class to convert the string to an integer.
main.py
my_int = 1357 result_2 = int(str(my_int)[:-1]) print(result_2) # 👉️ 135

We used the str() class to convert the integer to a string, so we can get a slice of the string.

The syntax for string slicing is my_str[start:stop:step] where the start value is inclusive, and the stop value is exclusive.

The stop index in the example is negative, meaning go up to, but not including the last character in the string.

main.py
my_int = 1357 print(str(my_int)[:-1]) # 👉️ '135'

If you need to remove the last two digits from the integer, you can update the stop index to -2.

main.py
my_int = 1357 print(str(my_int)[:-2]) # 👉️ '13'

The last thing we have to do is convert the string to an integer.

main.py
my_int = 1357 result_2 = int(str(my_int)[:-1]) print(result_2) # 👉️ 135

The int class returns an integer object constructed from the provided number or string argument.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.