0

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?

5
Contributors
6
Replies
13
Views
6 Years
Discussion Span
Last Post by spesseh
Featured Replies
  • if digit is in string form: [icode]digit[:1][/icode] if the digit is an integer: [icode]str(digit)[:1][/icode] *or even easier: [icode]str(digit)[0][/icode] Read More

1

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

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)
0

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
0

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?

0

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.