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?

8 Years
Discussion Span
Last Post by spesseh

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

Edited by Kruptein: easier solution


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?


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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.