Get the first digit of a number in Python

Borislav Hadzhiev

Last updated: Sep 23, 2022

Photo from Unsplash

**To get the first digit of a number:**

- Use the
`str()`

class to convert the number to a string. - Access the character at index
`0`

. - Use the
`int()`

class to convert the result to an integer.

main.py

`num = 246810 first = int(str(num)[0]) print(first) # 👉️ 2`

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`

.

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`

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.

Which approach you pick is a matter of personal preference. I'd go with
converting the number to a string and accessing it at index `0`

because I find
it quite intuitive and more readable.