How to Get the First Digit of a Number in Python

Are you working on a Python coding project and need to know how to extract the first digit of a number? This tutorial is designed to help you through it.

Python is a high-level, object-oriented programming language that has built-in data types, making it an excellent choice for data manipulation and analysis. Let’s see how you can use some of its built-in functions to find the first digit of a number in Python.

Step 1: Convert the Number to a String

Python comes with built-in functions to convert values between different data types. For this task, we will use the str() function which converts an integer to a string.

The first line creates an integer, and the second line converts it to a string.

Step 2: Find the first character of the string

Next, we find the first character of the string. As Python treats strings as arrays of bytes, we can access the characters directly using index numbers. For example, in Python, the first character of a string is at index 0. We’ll pull out the first character like this:

Step 3: Convert the String Back to an Integer

The first digit of the number is currently a string. To convert it back to an integer, you can use Python’s built-in int() function like this:

Output

'12345'
'1'
1

Complete Code

Bringing it all together, we have:

Conclusion

The ability to manipulate and analyze data is a key skill in Python programming. We hope this guide has helped you understand how to find the first digit of a number in Python using its built-in functions.

Keep exploring Python’s powerful features to make your coding journey easier and more exciting.