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.
1 2 3 |
num = 12345 num_as_str = str(num) print(num_as_str) |
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:
1 2 |
first_char = num_as_str[0] print(first_char) |
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:
1 2 |
first_digit = int(first_char) print(first_digit) |
Output
'12345' '1' 1
Complete Code
Bringing it all together, we have:
1 2 3 4 5 |
num = 12345 num_as_str = str(num) first_char = num_as_str[0] first_digit = int(first_char) print(first_digit) |
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.