Get part of an integer in Python

Is there an elegant way (possibly in numpy) to get the given part of a Python integer, for example, I want to get 90from 1990.

I can do:

my_integer = 1990
int(str(my_integer)[2:4])
# 90

But that is pretty ugly.

Any other option?

+4
source share
4 answers

1990 % 100 will do the trick.

(It %is a modular operator and returns the rest of the division, here 1990 = 19 * 100 + 90.)


Added after the answer was accepted:

If you need something in common, try the following:

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 digit i (as an int), i.e.

>>> GetIntegerSlice(123456, 3, 4)
34

Not sure if this is an improvement over your suggestion, but it doesn't rely on string operations and it was interesting to write.

(: int ( int ) .)

+9

:

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
+4

Depends on the use, but if, for example, you know that you want only the last two, you can use the module operator as follows: 1990%100to get 90.

+3
source

Maybe so:

my_integer = 1990
my_integer % 100
+3
source

All Articles