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?

2
  • What exactly are you trying to achieve? Commented Apr 2, 2016 at 20:43
  • i want to get part of an integer, as explained in my question. Commented Apr 2, 2016 at 20:46

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

That's why I asked him.
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 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).
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 

Comments

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.

Comments

3

Maybe like this:

my_integer = 1990 my_integer % 100 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.