Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get part of an integer in Python

Tags:

python

integer

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?

like image 366
tagoma Avatar asked Dec 01 '22 16:12

tagoma


2 Answers

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

like image 110
fuenfundachtzig Avatar answered Jan 18 '23 14:01

fuenfundachtzig


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
like image 21
MaxU - stop WAR against UA Avatar answered Jan 18 '23 13:01

MaxU - stop WAR against UA