To get the last digit of a number in Python:
- Access the string representation of the number.
- Get the last character of the string representation.
- Convert the character to an integer.
For example, let’s get the last digit of 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
Conclusion
Today you learned how to get the last number from a digit.
To recap, get the string representation of the number, access the last character, and convert it back to integer.
Thanks for reading. Happy coding!
Further Reading
How to Write to a File in Python
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
Artificial Intelligence2023.03.14Best AI Tools of 2023 (Save Time & Boost Productivity)
Python2023.02.16How to Pass a Variable from HTML Page to Another (w/ JavaScript)
JavaScript2023.02.16JavaScript How to Get Selected Text from a Textbox
JavaScript2023.02.15JavaScript Select All Text in Div with a Mouse Click