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.)
Here is generic function for getting any number of last digits:
In [160]: def get_last_digits(num, digits=2):
.....: return num%10**digits
.....:
In [161]: get_last_digits(1999)
Out[161]: 99
In [162]: get_last_digits(1999,3)
Out[162]: 999
In [166]: get_last_digits(1999,10)
Out[166]: 1999
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With