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?

## Recommended Answers

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

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
realNumber = locale.atoi(firstNum)``````

## 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)`

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
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)
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 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.