Handle positive and negative integers correctly:
>>> x = -23457689 >>> print abs(x) % 1000 689
As a function in which you can select the number of leading digits:
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 restriction to avoid converting to str too pedantic. Converting to str would be a good way to do this if the format of the number can change or the format of the digits to be saved is changed.
>>> int(str(x)[-3:]) ^^^^^ Easier to modify this than shoe-horning the mod function.
source share