How to get the first digit of a number in Python
Learn how to get the first digit of a number in Python. This guide covers multiple methods, real-world uses, and common debugging tips.
.png)
It's a common task in Python to find the first digit of a number, often for data validation or sorting. The language provides simple methods using both math and string manipulation.
In this article, you'll explore several techniques to isolate the first digit. We'll provide practical tips, real-world use cases, and debugging advice to help you apply this skill effectively.
Using the str() function and string indexing
number = 7392
first_digit = int(str(abs(number))[0])
print(f"First digit of {number} is {first_digit}")--OUTPUT--First digit of 7392 is 7
This method's strength lies in its simplicity. It converts the number into a string, allowing you to treat it like any other text sequence and grab the first character. It's a clean and readable way to solve the problem.
Here’s the breakdown of the core logic:
- First,
abs()handles negative values, preventing the minus sign from being selected. - Next,
str()converts the number to a string. - Then, index
[0]accesses the first character. - Finally,
int()converts that character back to an integer.
Mathematical approaches
If you'd rather avoid string conversion, you can use purely mathematical methods involving logarithms, integer division, or even recursion to get the same result.
Using logarithm with math.log10()
import math
number = 7392
magnitude = math.floor(math.log10(abs(number)))
first_digit = number // 10**magnitude
print(f"First digit of {number} is {first_digit}")--OUTPUT--First digit of 7392 is 7
This mathematical approach cleverly determines the number's scale to find the first digit. It's a bit like figuring out how many zeros you'd need after a 1 to get a number of the same size.
- The
math.log10()function finds the exponent for 10 that would produce your number. Usingmath.floor()on this result gives you the number of digits minus one. - With that magnitude, you can use integer division (
//) to divide the original number by 10 to that power, which neatly leaves only the first digit.
Using integer division with // operator
number = 7392
temp = abs(number)
while temp >= 10:
temp //= 10
print(f"First digit of {number} is {temp}")--OUTPUT--First digit of 7392 is 7
This iterative approach uses a while loop to repeatedly chop off the last digit of the number. The process continues until only the first digit is left.
- The loop runs as long as the number is
10or greater, which confirms it has more than one digit. - Inside the loop, the integer division operator (
//) divides the number by 10, effectively removing the final digit with each pass.
When the number becomes less than 10, the loop terminates, leaving you with the original first digit.
Using recursion to find first digit
def get_first_digit(n):
n = abs(n)
return n if n < 10 else get_first_digit(n // 10)
number = 7392
print(f"First digit of {number} is {get_first_digit(number)}")--OUTPUT--First digit of 7392 is 7
This recursive solution mirrors the logic of the while loop but packages it into a function that calls itself. The get_first_digit function keeps stripping the last digit until only one remains.
- The function's base case is when the number is less than
10. At this point, the recursion stops and returns the single-digit number. - If the number is
10or greater, the function calls itself with the result ofn // 10, effectively passing a smaller version of the number to the next call.
Advanced techniques
Building on the previous methods, you can also leverage Python’s expressive syntax for more compact solutions, like one-liners, list comprehensions, and regular expressions.
Creating a one-liner with length calculation
number = 7392
first_digit = abs(number) // (10 ** (len(str(abs(number))) - 1))
print(f"First digit of {number} is {first_digit}")--OUTPUT--First digit of 7392 is 7
This compact one-liner cleverly mixes string and math operations. It calculates the number of digits by converting the number to a string and checking its length with len(). That length is then used to create the right divisor to isolate the first digit.
- The expression
len(str(abs(number))) - 1determines the number's magnitude. For a four-digit number, this gives you 3. - Using this result as an exponent for
10, you can use integer division (//) to leave just the first digit.
Using list comprehension for digit extraction
number = 7392
digits = [int(d) for d in str(abs(number))]
first_digit = digits[0]
print(f"First digit of {number} is {first_digit}")--OUTPUT--First digit of 7392 is 7
A list comprehension offers a concise way to build a list from another sequence. This method iterates through the string version of your number, converting each character back into an integer and storing it in a new list called digits.
- The expression
[int(d) for d in str(abs(number))]effectively unpacks the number into a list of its individual digits. - From there, you can simply access the first element with the index
[0]to get your result.
This is a very readable and Pythonic solution, though it processes every digit instead of stopping at the first one.
Using regular expressions to match the first digit
import re
number = 7392
match = re.search(r'^\d', str(abs(number)))
first_digit = int(match.group())
print(f"First digit of {number} is {first_digit}")--OUTPUT--First digit of 7392 is 7
Regular expressions offer a powerful way to find patterns in text. Using Python's re module, the re.search() function looks for the pattern r'^\d' within the string version of the number.
- The
^symbol in the pattern anchors the search to the beginning of the string. - The
\dtoken matches any single digit, so the pattern effectively says, "find the first character if it's a digit". - If successful,
re.search()returns a match object. You then usematch.group()to extract the matched character andint()to convert it to a number.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the digit-finding techniques we've explored, Replit Agent can turn them into production-ready tools:
- Build a data validation utility that checks if account numbers or identifiers start with a specific digit, which is useful for systems like credit card processing.
- Create a fraud detection dashboard that analyzes datasets for anomalies using Benford's Law, a principle that predicts the frequency of first digits in real-world data.
- Deploy a sorting tool that categorizes large sets of numbers into buckets based on their leading digit, which can optimize certain data retrieval algorithms.
You can take any of these ideas from concept to a deployed application just by describing it. Try Replit Agent and watch it write, test, and deploy your code automatically.
Common errors and challenges
While these methods are powerful, a few common pitfalls can trip you up if you're not careful with edge cases.
Handling negative numbers with str()[0]
If you use the string conversion method without handling negative numbers, you'll get the minus sign instead of the first digit. Calling str() on -456 produces the string '-456', so indexing with [0] returns '-'. You can prevent this by always using the abs() function first to get the number's absolute value.
Avoiding math domain errors with log10()
The math.log10() function is a sharp tool, but it only works for positive numbers. If you pass it a zero or a negative value, Python will raise a ValueError. To build robust code, you should always check for these edge cases before making the call, for instance by handling zero as a special case and using abs() for negatives.
Handling non-numeric first characters
Your code might also fail if it receives input that isn't a clean number, like a string containing a currency symbol. For example, trying to find the first digit of '$199' will cause an error when a function like int() encounters the '$'. It's a good habit to validate or sanitize your input to ensure you're only processing digits.
Handling negative numbers with str()[0]
Without the abs() function, converting a negative number to a string places the minus sign at the start. This means indexing with [0] grabs the sign instead of the first digit, which will cause a ValueError. See it in action below.
def first_digit(num):
return int(str(num)[0])
print(first_digit(7392))
print(first_digit(-123)) # Will return "-" not "1"
The int() function expects a string containing only digits. Because str(-123)[0] evaluates to the character '-', the conversion fails and raises an error. The corrected implementation below handles this case properly.
def first_digit(num):
return int(str(abs(num))[0])
print(first_digit(7392))
print(first_digit(-123)) # Now returns "1"
The corrected code uses the abs() function to handle negative inputs gracefully. By getting the number's absolute value first, you ensure the string conversion doesn't include a minus sign. This prevents str(num)[0] from grabbing the sign and causing a ValueError when int() tries to convert it. It's a crucial check whenever your function might encounter negative numbers, making your code more reliable.
Avoiding math domain errors with log10()
The math.log10() method is powerful, but it has a critical weakness: it only works on positive numbers. If you feed it a zero or a negative value, Python will raise a ValueError because the operation is mathematically undefined. The following code snippet illustrates this problem by passing a zero to a function that isn't prepared for it.
import math
def first_digit(num):
magnitude = math.floor(math.log10(num))
return num // 10**magnitude
print(first_digit(7392))
print(first_digit(0)) # ZeroDivisionError: math domain error
The function crashes because passing 0 to math.log10() is an undefined operation, triggering a ValueError. Check out the corrected implementation below, which gracefully handles this edge case.
import math
def first_digit(num):
if num == 0:
return 0
num = abs(num)
magnitude = math.floor(math.log10(num))
return num // 10**magnitude
print(first_digit(7392))
print(first_digit(0))
The corrected function first checks if the input num is 0. If so, it immediately returns 0 to avoid the illegal operation. For all other numbers, it uses abs() to handle potential negatives. This two-step validation—checking for zero and taking the absolute value—ensures only positive numbers reach math.log10(), preventing a ValueError. It's a crucial safeguard whenever you use a mathematical function with a limited domain.
Handling non-numeric first characters
When your input isn't a pure number, simple string conversion can fail. If a string like "A123" is passed, the int() function can't convert the leading letter 'A' into a number, which triggers a ValueError. The code below demonstrates this problem.
def first_digit(value):
return int(str(value)[0])
print(first_digit(7392))
print(first_digit("A123")) # ValueError: invalid literal for int()
The function assumes the first character of any input will be a digit. When it gets "A123", the int() function receives 'A' and fails, as it can only convert numeric characters. See the corrected implementation below.
def first_digit(value):
s = str(value)
for char in s:
if char.isdigit():
return int(char)
return None
print(first_digit(7392))
print(first_digit("A123")) # Returns 1 instead of error
The corrected first_digit function is much safer. It loops through the input string and uses char.isdigit() to check each character. The moment it finds the first actual digit, it returns that number. If the loop finishes without finding any digits, it returns None. This is a great way to handle unpredictable input, especially when dealing with data from external sources like files or user entries, which might not be perfectly clean.
Real-world applications
Beyond the code and its potential pitfalls, these techniques are used for practical tasks like identifying card providers and analyzing data patterns.
Identifying card providers using the str()[0] technique
The str()[0] technique offers a simple way to identify a card's provider, as the first digit of a credit card number often corresponds to a specific payment network like Visa or Mastercard.
def identify_card_provider(card_number):
first_digit = int(str(card_number)[0])
providers = {4: "Visa", 5: "Mastercard", 3: "American Express", 6: "Discover"}
return providers.get(first_digit, "Unknown provider")
card_number = 4123456789012345
print(f"Card {card_number} is from {identify_card_provider(card_number)}")
The identify_card_provider function uses a dictionary to map a number's first digit to a provider name. It isolates the leading digit by converting the number to a string, grabbing the first character, and turning it back into an integer.
- A dictionary called
providersstores the mapping between digits and company names. - The
.get()method looks up the digit. This is a safe approach because it won't crash if the digit isn't found. Instead, it returns the default value, "Unknown provider".
This makes the function robust against unexpected card numbers.
Analyzing data patterns with int(str(num)[0])
You can also use the int(str(num)[0]) method in a list comprehension to quickly analyze the distribution of first digits in a dataset, a technique often used to spot anomalies in financial data.
financial_data = [1463, 589, 2917, 1292, 874, 1235, 3271, 965, 1482, 7201]
first_digits = [int(str(num)[0]) for num in financial_data]
digit_count = {d: first_digits.count(d) for d in range(1, 10)}
print(f"First digit distribution: {digit_count}")
print(f"Most common first digit: {max(digit_count, key=digit_count.get)}")
This code snippet efficiently analyzes a list of numbers to find the most common leading digit. It uses two comprehensions for a compact and readable solution.
- A list comprehension builds
first_digitsby isolating the first digit of each number in the dataset. - A dictionary comprehension then creates
digit_count, which tallies how many times each digit (1-9) appears.
Finally, max(digit_count, key=digit_count.get) finds the digit with the highest frequency. It’s the key argument that makes this possible, telling max() to compare dictionary values instead of keys.
Get started with Replit
Turn these techniques into a real tool with Replit Agent. Describe what you want, like “a utility that validates SKUs by their first digit” or “a dashboard that visualizes first-digit distribution in a dataset.”
Our AI agent will write the code, test for errors, and deploy your application automatically. Start building with Replit and bring your idea to life in minutes.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.


.png)
.png)