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
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
str(r)[0]
This converts it to a string first.
And if you need it as an int:
int(str(r)[0])
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))))