Getting the first digit of an integer?

So if r = 54, how can I get the first digit. I thought r[0] would work, but apparently not:

TypeError: 'int' object is unsubscriptable

This converts it to a string first.

And if you need it as an int:


Small annotation: this method fails for negative numbers, i. g. -10. You should add a call to abs().

Here is an alternate way which works for all integer numbers. The intersting thing is that this way is slower than the str() method for numbers with 4+ digist, and faster for numbers with 3 or less digist.

def first_digit(i):
  i = abs(i)
  while i >= 10:
    i //= 10
  return int(i)

Another interesting method, which works only for positive numbers (1…), but is even slower:

def first_digit(i): 
  return i // (10 ** int(math.floor(math.log10(i))))