Skip to content

How to Extract the K-th Rightmost Digit from an Integer in Python

Learn how to extract the k-th digit from the right side of an integer in Python using string conversion and negative indexing for precise position-based access.

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:

  1. String Conversion: Convert the number to a string and use negative indexing.
  2. 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.

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:
    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

n_str = str(n)

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.
    """
    n_str = str(n)

    if k > len(n_str) or k <= 0:
        return None  # Or raise an IndexError

    digit_char = n_str[-k]

    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

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):
    shifted = n // (10 ** (k - 1))
    
    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:

  1. Convert the integer to a string: s = str(n).
  2. Access via negative index: digit_char = s[-k].
  3. Cast back to integer: int(digit_char).

This approach is concise and leverages Python's intuitive sequence manipulation syntax.

Navigation