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
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
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])
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.
If you want a solution that avoids str
and recursion consider:
from math import log10
n = 1010
n // (10 ** int(log10(n)))
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