Hi all.

This is probably quite a newbish question, but i have a input for a number. From the entered number, i want to extract the first digit in the number. So if the typed in number is 43, i want to extract the 4, but not the 3. In another program i would think of a left operation to extract the lefternmost digit. However i cannot make this work in python.
How would one write such a extract operation?

Dani AI

Generated

Two common interpretations of "first digit" are worth distinguishing: the leftmost character in the user input string, and the most significant digit of a numeric value. Also consider edge cases like a leading sign (e.g., "-42"), whitespace, decimals, and zero. In Python 3, remember to use input() rather than raw_input().

If you want the most significant digit of an integer without converting to a string, use integer arithmetic. This works for arbitrary-sized ints and handles negatives and zero:

def first_digit_int(n: int) -> int:
    n = abs(n)
    if n == 0:
        return 0
    while n >= 10:
        n //= 10
    return n

If you want the first digit character that appears anywhere in a user-entered string (ignoring signs, spaces, or currency symbols), a regex is robust:

import re

def first_digit_in_text(s: str) -> int:
    m = re.search(r"\d", s)
    if not m:
        raise ValueError("No digit found")
    return int(m.group())

When input may include locale-specific thousands separators or decimal commas, parse using the current locale and then extract the most significant digit from the resulting number. The locale module is not deprecated; locale.atoi/atof are still supported and documented in the standard library (Python locale docs). For regex details, see re.search.

Recommended Answers

All 6 Replies

if digit is in string form: digit[:1] if the digit is an integer: str(digit)[:1] *or even easier: str(digit)[0]

If you need it to be an integer you could use atoi() from the locale to pull it from the string. Use atof() for float points.

import locale
nmbr = raw_input("enter a number")
firstNum = nmbr[0]
realNumber = locale.atoi(firstNum)

That is making it more difficult than it need to be Tech B.

n = raw_input('enter a number: ')
first_n = int(n[0])
print first_n

I keep forgetting about int().... And yeah that would be a simpler way lol. Then what use would locale.atoi() be if int() serves the same purpose?

I believe that whole module was deprecated as of version 2 or so. I think anyways.

Thanks! Worked great by using the string and then slice it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.