Get last three digits of an integer

只谈情不闲聊 提交于 2019-11-28 12:13:18

Use the % operation:

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

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

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!