1

Is it possible, to the the first digit of a integer, for example: num = 1010 , so you take the 1 from the num variable out and put it into another integer?

for example:

num = 1010 num_2 = (first digit of num) num_2 + 2 * 2 
2

4 Answers 4

2

If you want a solution that avoids str and recursion consider:

from math import log10 n = 1010 n // (10 ** int(log10(n))) 
Sign up to request clarification or add additional context in comments.

2 Comments

This is subject to errors from float precision. For example, it does not work for n = 999999999999999 given 64bit floats.
That's interesting and good to know. This particular case seems to go away with replacing log10(n) with log(n, 10) but can be reproduced with even more 9's. I don't know enough about the implementation of log10 to understand further (just log2(n) / log2(10)?). I can see that this approach generally will be sensitive to float error in calculating the number of base 10 digits of n.
1

Yes, you can convert it to a string, take the first character of that string, then convert that to an int.

num = 1010 num_2 = int(str(num)[0]) 

Comments

1

Use re.sub like so:

import re num2 = int(re.sub(r'(.).*', '\\1', str(num))) 

This removes all but the first digit of num. The str conversion is needed for re.sub to work (it requires a string), and the int conversion is needed for subsequent arithmetic operations to work.

Comments

0

Or if you want to do it the hard way, divide the number by 10 until the result is less than 10:

def first_digit(n): while n > 10: n //= 10 return n 

Comments