5

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?

tagoma
  • 3,896
  • 4
  • 38
  • 57

4 Answers4

10

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.)

fuenfundachtzig
  • 7,952
  • 13
  • 62
  • 87
  • That's why I asked him. – fuenfundachtzig Apr 02 '16 at 20:52
  • 1
    UpperCamelCase is a **terrible** naming convention for a Python function, don't show this stuff to beginners and stop writing it. See [this PEP8 reference](https://www.python.org/dev/peps/pep-0008/#function-names) to see what the "standard" is. Even if you don't want to write lowercase with underscores, don't do upper camel case. It is a disgrace (in Python). – Bernardo Sulzbach Apr 06 '16 at 00:26
4

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
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
3

Depends on the use but if you for example know you only want the last two you can use the modulus operator like so: 1990%100 to get 90.

Ulf Aslak
  • 7,876
  • 4
  • 34
  • 56
3

Maybe like this:

my_integer = 1990
my_integer % 100
mvidovic
  • 321
  • 5
  • 9