12

I wish to change an integer such as 23457689 to 689, 12457245 to 245 etc.

I do not require the numbers to be rounded and do not wish to have to convert to String.

Any ideas how this can be done in Python 2.7?

vaultah
  • 44,105
  • 12
  • 114
  • 143
Luke Gatt
  • 169
  • 1
  • 2
  • 12

2 Answers2

24

Use the % operation:

>>> x = 23457689
>>> x % 1000
689

% is the mod (i.e. modulo) operation.

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
11

To handle both positive and negative integers correctly:

>>> x = -23457689
>>> print abs(x) % 1000
689

As a function where you can select the number of leading digits to keep:

import math
def extract_digits(integer, digits=3, keep_sign=False):
    sign = 1 if not keep_sign else int(math.copysign(1, integer))
    return abs(integer) % (10**digits) * sign

The constraint to avoid converting to str is too pedantic. Converting to str would be a good way to do this if the format of the number might change or if the format of the trailing digits that need to be kept will change.

>>> int(str(x)[-3:])
              ^^^^^ Easier to modify this than shoe-horning the mod function.
ely
  • 74,674
  • 34
  • 147
  • 228
  • Thanks, but I was simply required to extract the last digits and plot, the values would never change. I could use this as well – Luke Gatt Feb 17 '15 at 20:36
  • 3
    "the values would never change..." said every programmer ever. – ely Feb 17 '15 at 20:37
  • I like this answer because it brings up the issue of possibly negative input, and because it gives the string-based alternative. However, I don't like that it makes an assumption about how negative input should be handled (what if they want to keep the sign, for example?), and I disagree that the string slicing is any "easier to modify" than the mod function. – John Y Feb 17 '15 at 20:45