Python 获取整数的最后三位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28570505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get last three digits of an integer
提问by Luke Gatt
I wish to change an integer such as 23457689 to 689, 12457245 to 245 etc.
我希望将 23457689 之类的整数更改为 689,将 12457245 更改为 245 等。
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?
任何想法如何在 Python 2.7 中完成?
回答by Warren Weckesser
回答by ely
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.
避免转换为的约束str
过于迂腐。str
如果数字的格式可能会发生变化,或者需要保留的尾随数字的格式会发生变化,那么转换为将是一个很好的方法。
>>> int(str(x)[-3:])
^^^^^ Easier to modify this than shoe-horning the mod function.