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

4 Answers4

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])
khelwood
  • 55,782
  • 14
  • 81
  • 108
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.

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
1

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

from math import log10

n = 1010
n // (10 ** int(log10(n)))
Kyle Parsons
  • 1,475
  • 6
  • 14
  • 1
    This is subject to errors from float precision. For example, it does not work for ``n = 999999999999999`` given 64bit ``float``s. – MisterMiyagi Oct 15 '21 at 14:49
  • 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. – Kyle Parsons Oct 15 '21 at 16:12
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
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252