Is there an elegant way (maybe in numpy) to get a given part of a Python integer, eg say I want to get 90 from 1990.
I can do:
my_integer = 1990 int(str(my_integer)[2:4]) # 90 But it is quite ugly.
Any other option?
Is there an elegant way (maybe in numpy) to get a given part of a Python integer, eg say I want to get 90 from 1990.
I can do:
my_integer = 1990 int(str(my_integer)[2:4]) # 90 But it is quite ugly.
Any other option?
1990 % 100 would do the trick.
(% is the modulo operator and returns the remainder of the division, here 1990 = 19*100 + 90.)
Added after answer was accepted:
If you need something generic, try this:
def GetIntegerSlice(i, n, m): # return nth to mth digit of i (as int) l = math.floor(math.log10(i)) + 1 return i / int(pow(10, l - m)) % int(pow(10, m - n + 1)) It will return the nth to mth digit of i (as int), i.e.
>>> GetIntegerSlice(123456, 3, 4) 34 Not sure it's an improvement over your suggestion, but it does not rely on string operations and was fun to write.
(Note: casting to int before doing the division (rather than only casting the result to int in the end) makes it work also for long integers.)