Get the first or first N digits of a Number in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
6 min

banner

# Table of Contents

  1. Get the first digit of a number in Python
  2. Get the first N digits of a number in Python
  3. Get only the first Number in a String in Python
  4. Find the index of the first Digit in a String in Python

# Get the first digit of a number in Python

To get the first digit of a number:

  1. Use the str() class to convert the number to a string.
  2. Access the character at index 0.
  3. Use the int() class to convert the result to an integer.
main.py
num = 246810 first = int(str(num)[0]) print(first) # ๐Ÿ‘‰๏ธ 2

get first digit of number

The code for this article is available on GitHub

If you need to get the first N digits of a number, click on the following subheading:

We used the str() class to convert the integer to a string so we can access the string at a specific index.

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

The next step is to access the character at index 0 to get the first digit of the number.

Once we have the first digit, we can use the int() class to convert the string to an integer.

main.py
num = 246810 first = int(str(num)[0]) print(first) # ๐Ÿ‘‰๏ธ 2

You can use the same approach if you need to get the first N digits of a number.

main.py
num = 246810 first2 = int(str(num)[:2]) print(first2) # ๐Ÿ‘‰๏ธ 24 first3 = int(str(num)[:3]) print(first3) # ๐Ÿ‘‰๏ธ 246

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

The slice my_str[:2] starts at index 0 and goes up to, but not including index 2.

# Get the first digit of a number using recursion

Alternatively, you can use recursion.

main.py
def get_first_digit(number): if number < 10: return number return get_first_digit(number // 10) print(get_first_digit(2468)) # ๐Ÿ‘‰๏ธ 2 print(get_first_digit(514)) # ๐Ÿ‘‰๏ธ 5 print(get_first_digit(14)) # ๐Ÿ‘‰๏ธ 1 print(get_first_digit(8)) # ๐Ÿ‘‰๏ธ 8

get first digit of number using recursion

The code for this article is available on GitHub

The function checks if the number is less than 10 and if the condition is met, it returns the number.

Otherwise, it returns the result of calling itself with the number floor-divided by 10.

Division / of integers yields a float, while floor division // of integers results in an integer.

The result of using the floor division operator is that of a mathematical division with the floor() function applied to the result.

main.py
my_num = 50 print(my_num / 5) # ๐Ÿ‘‰๏ธ 10.0 (float) print(my_num // 5) # ๐Ÿ‘‰๏ธ 10 (int)

We divide the number by 10 until we get a single-digit number and return the result.

# Get the first N digits of a number in Python

To get the first N digits of a number:

  1. Use the str() class to convert the number to a string.
  2. Use string slicing to select the first N characters of the string.
  3. Use the int() class to convert the result to an integer.
main.py
number = 13579 # โœ… Get the first 2 digits of a number first_2 = int(str(number)[:2]) print(first_2) # ๐Ÿ‘‰๏ธ 13 # โœ… Get the first 3 digits of a number first_3 = int(str(number)[:3]) print(first_3) # ๐Ÿ‘‰๏ธ 135

get first n digits of number

The code for this article is available on GitHub

We used the str() class to convert the integer to a string so we can use string slicing.

The first example returns the first two digits of the number.

The slice my_str[:2] starts at index 0 and goes up to, but not including index 2.

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

Once we have the first 2 digits, we use the int() class to convert the string to an integer.

main.py
number = 13579 first_2 = int(str(number)[:2]) print(first_2) # ๐Ÿ‘‰๏ธ 13

# Get the first N digits of a number using recursion

Alternatively, you can use recursion.

main.py
def get_first_two_digits(number): if number < 100: return number return get_first_two_digits(number // 10) print(get_first_two_digits(2468)) # ๐Ÿ‘‰๏ธ 24 print(get_first_two_digits(514)) # ๐Ÿ‘‰๏ธ 51 print(get_first_two_digits(95)) # ๐Ÿ‘‰๏ธ 95 print(get_first_two_digits(7)) # ๐Ÿ‘‰๏ธ 7

get first n digits of number using recursion

The code for this article is available on GitHub

The function checks if the number is less than 100 and if the condition is met, it returns the number.

Otherwise, it returns the result of calling itself with the number floor-divided by 10.

Division / of integers yields a float, while floor division // of integers results in an integer.

The result of using the floor division operator is that of a mathematical division with the floor() function applied to the result.

main.py
my_num = 50 print(my_num / 5) # ๐Ÿ‘‰๏ธ 10.0 (float) print(my_num // 5) # ๐Ÿ‘‰๏ธ 10 (int)

We divide the number by 10 until we get a 2-digit number and return the result.

If you need to get the first three digits of the number, you would check if the number is less than 1000.

main.py
def get_first_three_digits(number): if number < 1000: return number return get_first_three_digits(number // 10) print(get_first_three_digits(2468)) # ๐Ÿ‘‰๏ธ 246 print(get_first_three_digits(51410)) # ๐Ÿ‘‰๏ธ 514 print(get_first_three_digits(95799)) # ๐Ÿ‘‰๏ธ 957 print(get_first_three_digits(719292)) # ๐Ÿ‘‰๏ธ 719

# Get only the first Number in a String in Python

If you need to get only the first number in a string, use re.search().

main.py
import re my_str = 'bobby12hadz34.com' match = re.search(r'\d+', my_str) if match: # ๐Ÿ‘‡๏ธ First number found: 12 print('First number found:', match.group()) # ๐Ÿ‘‡๏ธ Index of first digit: 5 print('Index of first digit:', match.start()) else: print('The string does NOT contain any numbers')

get only first number in string

The code for this article is available on GitHub

The re.search() method looks for the first location in the string where the provided regular expression produces a match.

If the re.search() method finds a match, it will return a match object, otherwise None is returned.

The first argument we passed to the re.search() method is a regular expression.

The \d character matches the digits [0-9] (and many other digit characters).

The + matches the preceding character (a digit) 1 or more times.

You can use the start() method on the match object to get the index of the first digit in the string.

If you ever need help reading or writing a regular expression, consult the regular expression syntax subheading in the official docs.

The page contains a list of all of the special characters with many useful examples.

We used the match.group() method to get the entire match.

Make sure to use an if statement before calling the match.group() method. The re.search() method would return None if the string doesn't contain any numbers.

You can also use a range of digits [0-9] if you find the regular expression more readable.

main.py
import re my_str = 'bobby12hadz34.com' match = re.search(r'[0-9]+', my_str) if match: # ๐Ÿ‘‡๏ธ First number found: 12 print('First number found:', match.group()) else: print('The string does NOT contain any numbers')

The square brackets [] are used to indicate a set of characters.

The 0-9 characters match the digits in the range.

# Find the index of the first Digit in a String in Python

To find the index of the first digit in a string:

  1. Use a for loop to iterate over the string with enumerate().
  2. Use the str.isdigit() method to check if each character is a digit.
  3. Once the index is found, use the break statement to break out of the loop.
main.py
my_str = 'bobby123hadz' for index, char in enumerate(my_str): if char.isdigit(): print(index, char) # ๐Ÿ‘‰๏ธ 5, 1 break
The code for this article is available on GitHub

We used the enumerate() function to get access to the index of the current iteration.

The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.

main.py
my_str = 'bobby' for index, char in enumerate(my_str): print(char, index) # ๐Ÿ‘‰๏ธ b 0, o 1, b 2, b 3, y 4
On each iteration, we use the str.isdigit() method to check if the current character is a digit.

The str.isdigit() method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

main.py
print('A'.isdigit()) # ๐Ÿ‘‰๏ธ False print('5'.isdigit()) # ๐Ÿ‘‰๏ธ True

Once we find a digit, we use the break statement to break out of the loop.

main.py
my_str = 'bobby123hadz' for index, char in enumerate(my_str): if char.isdigit(): print(index, char) # ๐Ÿ‘‰๏ธ 5, 1 break

The break statement breaks out of the innermost enclosing for or while loop.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev