How to Get the First Digit of a Number in Python

AuthorSumit Dey Sarkar

Pubish Date11 Apr 2023

categoryPython

In this tutorial we will learn how to how to get the first digit of a number in python.

 

How to Get the First Digit of a Number in Python

To get the first digit of a number in Python, you can use a combination of division and floor division.

Here's an example:

 

number = 12345
first_digit = int(str(number)[0])
print(first_digit) # Output: 1

In this example, we have given  value 12345 to variable number. Then we convert number to a string using str(number) and extract the first character of the resulting string using [0]. We then convert this first character back to an integer using int(), giving us the value of the first digit. Since the first character of the string representation of 12345 is 1, the value of first_digit will be 1. We then print the value of first_digit using the print() function.

Comments 0

Leave a comment