Skip to main content

How to Extract Digits from Numbers and Strings in Python

This guide explains how to extract digits from numbers and strings in Python. We'll cover getting the first digit of an integer, the first N digits, the first sequence of digits within a larger string, and the index of the first digit in a string. We'll use a combination of string manipulation, mathematical approaches, and regular expressions.

Getting the First Digit of an Integer

The simplest way to get the first digit of an integer is to convert it to a string and access the first character:

num = 246810
first = int(str(num)[0]) # Convert to string, get first char, convert back to int
print(first) # Output: 2
  • The str() function transforms the integer into a string, which is then accessed using the index 0.

Using a Recursive Function (Less Efficient)

While less efficient than string conversion, a recursive approach can also be used:

def get_first_digit(number):
if number < 10:
return number # Base case: single-digit number
return get_first_digit(number // 10) # Recursively divide by 10

print(get_first_digit(2468)) # Output: 2
print(get_first_digit(514)) # Output: 5
print(get_first_digit(14)) # Output: 1
print(get_first_digit(8)) # Output: 8
  • The function uses recursion to go through all the digits until the number is a single digit number.

Getting the First N Digits of an Integer

Similar to getting the first digit, convert to a string and then use slicing:

number = 13579
first_2 = int(str(number)[:2]) # Get first two digits as a string, then convert
print(first_2) # Output: 13

first_3 = int(str(number)[:3])
print(first_3) # Output: 135
  • str(number)[:2]: Converts to a string and takes a slice of the first 2 characters.
  • int(...): Converts the sliced string back to an integer.

Using a Recursive Function (Less Efficient)

You can also use a recursive function that performs division:

def get_first_two_digits(number):
if number < 100:
return number
return get_first_two_digits(number // 10)
print(get_first_two_digits(2468)) # Output: 24

Finding and Extracting the First Number in a String

If your string contains a mix of digits and other characters, and you want to extract the first sequence of digits as a number, use regular expressions:

import re

my_str = 'tutorial12reference34.com'
match = re.search(r'\d+', my_str) # Find the first sequence of digits

if match:
first_number = int(match.group(0)) # Extract the matched digits and convert to int
print('First number found:', first_number) # Output: First number found: 12
print('Index of first digit:', match.start()) # Output: Index of first digit: 8
else:
print('The string does NOT contain any numbers')
  • re.search(r'\d+', my_str): Searches for the first occurrence of one or more digits (\d+) in the string.
  • r'\d+': The regular expression. \d matches any digit (0-9), and + means "one or more".
  • if match:: Checks if a match was found. re.search returns a match object if successful, and None otherwise.
  • match.group(0): Returns the entire matched substring (the number).
  • match.start() returns the index of the start of the match.
  • int(...): Converts the matched string to an integer.
  • The code also handles cases where there are no matches using the if statement.

Finding the Index of the First Digit in a String

To find the index of the first digit in a string, use a loop with enumerate() and isdigit():

my_str = 'tutorial123reference'
for index, char in enumerate(my_str):
if char.isdigit():
print(index, char) # Output: 8 1
break # Stop after the first digit is found
  • enumerate(my_str): Provides pairs of (index, character) for each character in the string.
  • char.isdigit(): Checks if the character is a digit.
  • break: Exits the loop immediately after the first digit is found.