Get the first Two digits of a number in Python

avatar

Borislav Hadzhiev

Last updated: Sep 23, 2022

banner

Photo from Unsplash

Get the first Two digits of a number in python #

To get the first two digits of a number:

  1. Use the str() class to convert the number to a string.
  2. Use string slicing to select the first 2 characters of the string.
  3. Use the int() class to convert the result to an integer.
main.py
number = 13579 first_2 = int(str(number)[:2]) print(first_2) # 👉️ 13

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

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

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

main.py
number = 13579 first_3 = int(str(number)[:3]) print(first_3) # 👉️ 135 first_4 = int(str(number)[:4]) print(first_4) # 👉️ 1357

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

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.

Which approach you pick is a matter of personal preference. I'd go with converting the number to a string and using string slicing because I find it quite intuitive and more readable.

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.