Skip to main content

How to Get Ones, Tens, Hundreds, Thousands Digits of a Number in Python

Extracting individual digits from a number based on their place value (ones, tens, hundreds, etc.) is a common task in programming, often required for calculations, formatting, or algorithmic challenges. Python offers several ways to achieve this, leveraging both mathematical operations and string manipulation.

This guide demonstrates three primary methods to isolate the digits of an integer: using mathematical operators, converting to a string, and employing a loop with division.

Understanding Place Value

Recall that in a number like 3217:

  • 7 is in the ones place (7 * 100)
  • 1 is in the tens place (1 * 101)
  • 2 is in the hundreds place (2 * 102)
  • 3 is in the thousands place (3 * 103)

Our goal is to extract these individual digits (7, 1, 2, 3).

Method 1: Mathematical Approach (% and //)

This method uses integer arithmetic – specifically the modulo (%) and floor division (//) operators – to isolate digits based on powers of 10.

Getting Specific Digits (Ones, Tens, etc.)

  • Ones Digit: The remainder when dividing by 10.

    number = 3217
    ones = number % 10
    print(f"Number: {number}") # Output: Number: 3217
    print(f"Ones Digit: {ones}") # Output: Ones Digit: 7
  • Tens Digit: Get the remainder when dividing by 100 (isolates last two digits), then floor divide by 10 (removes the ones digit).

    number = 3217
    tens = (number % 100) // 10
    print(f"Tens Digit: {tens}") # Output: Tens Digit: 1
    # Step-by-step: 3217 % 100 -> 17; 17 // 10 -> 1
  • Hundreds Digit: Get the remainder when dividing by 1000 (isolates last three digits), then floor divide by 100 (removes the ones and tens digits).

    number = 3217
    hundreds = (number % 1000) // 100
    print(f"Hundreds Digit: {hundreds}") # Output: Hundreds Digit: 2
    # Step-by-step: 3217 % 1000 -> 217; 217 // 100 -> 2
  • Thousands Digit: Floor divide by 1000 (removes the last three digits). For larger numbers, you'd use % 10000 // 1000.

    number = 3217
    thousands = number // 1000 # Only works if number < 10000 for this specific place

    # General approach for thousands place:
    thousands_general = (number % 10000) // 1000
    print(f"Thousands Digit: {thousands}") # Output: Thousands Digit: 3
    print(f"Thousands Digit (General): {thousands_general}") # Output: Thousands Digit (General): 3

Limitations

This method is effective for extracting digits from known place values. However, it becomes cumbersome if you need all digits from a number of unknown or variable length, as you'd need separate formulas for each potential place value.

Converting the number to a string allows you to treat each digit as an individual character. This is often the most flexible and readable approach for getting all digits.

Using List Comprehension

Convert the number to a string, then use a list comprehension to iterate over the string's characters, converting each back to an integer.

number = 3217

# Convert number to string and iterate through characters
# This gets digits in their natural order (most significant first)
digits_list = [int(digit_char) for digit_char in str(number)]

print(f"Number: {number}")
print(f"Digits (string conversion): {digits_list}")
# Output: Digits (string conversion): [3, 2, 1, 7]
  • str(number): Converts the integer to the string "3217".
  • [int(digit_char) for digit_char in ... ]: Iterates through each character ('3', '2', '1', '7') and converts it back to an integer using int().

Using a for Loop

The equivalent logic using a standard for loop:

number = 3217
digits_list_loop = []

for digit_char in str(number):
digits_list_loop.append(int(digit_char))

print(f"Digits (for loop): {digits_list_loop}")
# Output: Digits (for loop): [3, 2, 1, 7]

Getting Digits in Reverse Order

The string conversion methods naturally yield digits from left to right (most significant to least significant). If you specifically need the order [ones, tens, hundreds, thousands], simply reverse the resulting list:

number = 3217
digits_list = [int(digit_char) for digit_char in str(number)]

# Reverse the list to get [ones, tens, hundreds, thousands] order
digits_reversed = digits_list[::-1]
# Or: digits_reversed = list(reversed(digits_list))

print(f"Digits (Reversed Order): {digits_reversed}")
# Output: Digits (Reversed Order): [7, 1, 2, 3]
note

Reversing the final list of digits is often conceptually clearer.

Method 3: Iterative Division (while loop)

This method repeatedly extracts the last digit using the modulo operator and then removes that digit using floor division until the number becomes zero.

def get_digits_while(num):
"""Gets digits using iterative division (returns in ones, tens, ... order)."""
if num == 0:
return [0]
# Handle negative numbers by working with the absolute value
if num < 0:
num = abs(num) # Or handle sign separately if needed

digits = []
temp_num = num
while temp_num > 0:
last_digit = temp_num % 10 # Get the last digit (ones place of current number)
digits.append(last_digit)
temp_num //= 10 # Remove the last digit
return digits # Returns list like [ones, tens, hundreds...]

# Example Usage
number = 3217
digits_while = get_digits_while(number)
print(f"Number: {number}") # Output: Number: 3217
print(f"Digits (while loop): {digits_while}") # Output: Digits (while loop): [7, 1, 2, 3]
  • temp_num % 10: Isolates the rightmost digit (the ones digit of the current temp_num).
  • temp_num //= 10: Integer division removes the last digit.
  • The loop continues until temp_num becomes 0.
  • This method naturally produces the digits in order from least significant (ones) to most significant (thousands, etc.). If you need the natural order [3, 2, 1, 7], reverse the final list: return digits[::-1].

Handling Negative Numbers and Zero

  • Negative Numbers: The mathematical and while loop methods might produce unexpected results with the sign if not handled. Often, the easiest approach is to work with the absolute value first using abs(number) if you only care about the digit values. The string conversion method handles negative signs correctly (e.g., str(-123) is "-123"), so you might need to filter out the '-' character if only digits are needed.
  • Zero: The string conversion method yields [0]. The while loop needs a small adjustment (like the if num == 0: check added in the example) to handle input 0 correctly. The direct math method works fine for 0 (e.g., 0 % 10 is 0).

Choosing the Right Method

  • Method 1 (Mathematical): Best when you need only specific, known place values (e.g., just the hundreds digit) from numbers within a predictable range. Can be very fast for these specific cases. Less flexible for arbitrary numbers.
  • Method 2 (String Conversion): Most flexible and often most readable for getting all digits from numbers of any length. Easy to understand.
  • Method 3 (While Loop): A good mathematical alternative to string conversion for getting all digits. Useful if string conversion is undesirable for some reason. Naturally produces digits in reverse order (ones first).

Conclusion

Python provides multiple effective strategies for extracting the ones, tens, hundreds, and other digits from an integer:

  1. Mathematical operators (%, //) are precise for targeting specific known place values.
  2. String conversion (str()) followed by iteration (using list comprehension or a loop) is highly flexible for extracting all digits from numbers of varying lengths and is often the most readable approach.
  3. A while loop with modulo and floor division offers a purely mathematical way to extract all digits iteratively.

Choose the method that best suits your need for specific digits versus all digits, flexibility with number length, and code readability preferences. Remember to consider edge cases like negative numbers and zero.