How to Extract the K-th Rightmost Digit from an Integer in Python
Extracting a specific digit from an integer based on its position is a common algorithmic task, often used in problems involving checksums, reversing numbers, or cryptography.
In this guide, we will implement a function f(n, k) that returns the k-th digit from the right side of an integer n by utilizing Python's string manipulation capabilities.
Understanding the Logic
Integers in Python are mathematical entities, not sequences. You cannot access their digits by position (indexing) directly. To extract a digit, we have two primary options:
- String Conversion: Convert the number to a string and use negative indexing.
- Mathematical Operations: Use modulo
%and integer division//.
This guide focuses on the String Conversion method, as it is intuitive and leverages Python's powerful slicing features.
In Python lists and strings, negative indices count from the end. -1 is the last item, -2 is the second to last, and so on. This maps perfectly to "k-th digit from the right."
Step 1: Converting and Indexing
To access a digit, we first cast the integer to a string.
Problem with Direct Indexing
If you try to access a digit directly from an integer, Python raises an error.
n = 123456789
k = 3
try:
# ⛔️ Incorrect: Integers are not subscriptable (cannot be indexed)
digit = n[-k]
print(digit)
except TypeError as e:
print(f"Error: {e}")
Output:
Error: 'int' object is not subscriptable
Solution: String Conversion
By converting n to a str, we can treat it as a sequence of characters.
n = 123456789
k = 3
# ✅ Correct: Convert to string first
n_str = str(n)
# Access the character using negative indexing
# Index -3 corresponds to the 3rd char from the right
char_digit = n_str[-k]
print(f"Character found: '{char_digit}'")
print(f"Type: {type(char_digit)}")
Output:
Character found: '7'
Type: <class 'str'>
Step 2: Complete Function Implementation
We now wrap this logic into a reusable function f(n, k). We must ensure the returned value is converted back to an integer (int) so it can be used in mathematical calculations later.
def f(n, k):
"""
Return the k-th digit of the integer n from the right.
"""
# 1. Convert integer to string
n_str = str(n)
# 2. Check if k is within bounds (Optional but recommended)
if k > len(n_str) or k <= 0:
return None # Or raise an IndexError
# 3. Get the k-th digit using negative indexing
# If k=1, index is -1 (last char)
digit_char = n_str[-k]
# 4. Convert character back to integer
return int(digit_char)
if __name__ == "__main__":
number = 123456789
position = 3
result = f(number, position)
print(f"The {position}-rd digit from the right of {number} is: {result}")
Output:
The 3-rd digit from the right of 123456789 is: 7
If n is negative (e.g., -123), str(n) becomes "-123". The last character (-1) is still 3, but if k equals the length of the string, you might accidentally extract the - sign. For robustness, consider using str(abs(n)).
Alternative: Mathematical Approach
While string conversion is readable, doing this mathematically is often faster for computers as it avoids memory allocation for new strings.
The formula to get the k-th digit from the right is: Digit = (n // 10^(k-1)) % 10 where // is integer division and % is the modulo/remainder operator
def f_math(n, k):
# ✅ Correct: Math-only approach
# 1. Shift decimal point k-1 times to the right
shifted = n // (10 ** (k - 1))
# 2. Take the last digit
return shifted % 10
print(f"Math Result: {f_math(123456789, 3)}")
Output:
Math Result: 7
Conclusion
To extract the k-th digit from the right of a number in Python:
- Convert the integer to a string:
s = str(n). - Access via negative index:
digit_char = s[-k]. - Cast back to integer:
int(digit_char).
This approach is concise and leverages Python's intuitive sequence manipulation syntax.