Python 整数的最后2位?蟒蛇 3
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41664806/
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
Last 2 digits of an integer? Python 3
提问by Bathsheba
With my code, I want to get the last two digits of an integer. But when I make x a positive number, it will take the first x digits, if it is a negative number, it will remove the first x digits.
用我的代码,我想得到一个整数的最后两位数字。但是当我使 xa 为正数时,它将取前 x 位数字,如果是负数,它将删除前 x 位数字。
Code:
代码:
number_of_numbers = 1
num = 9
while number_of_numbers <= 100:
done = False
num = num*10
num = num+1
while done == False:
num_last = int(repr(num)[x])
if num_last%14 == 0:
number_of_numbers = number_of_numbers + 1
done = True
else:
num = num + 1
print(num)
回答by Bathsheba
Why don't you extract the absolute value of the number modulus 100? That is, use
你为什么不提取数模100的绝对值?也就是说,使用
abs(num) % 100
to extract the last two digits?
提取最后两位数字?
In terms of performance and clarity, this method is hard to beat.
在性能和清晰度方面,这种方法很难被击败。
回答by Moinuddin Quadri
Simpler way to extract last two digits of the number (less efficient)is to convert the number to str
and slice the last two digits of the number. For example:
提取数字最后两位数字的更简单方法(效率较低)是将数字转换为数字str
的最后两位数字并对其进行切片。例如:
# sample function
def get_last_digits(num, last_digits_count=2):
return int(str(num)[-last_digits_count:])
# ^ convert the number back to `int`
OR, you may achieve it via using modulo %
operator (more efficient), (to know more, check How does % work in Python?) as:
或者,您可以通过使用模%
运算符(更有效)来实现它,(要了解更多信息,请查看% 在 Python 中如何工作?)为:
def get_last_digits(num, last_digits_count=2):
return abs(num) % (10**last_digits_count)
# ^ perform `%` on absolute value to cover `-`ive numbers
Sample run:
示例运行:
>>> get_last_digits(95432)
32
>>> get_last_digits(2)
2
>>> get_last_digits(34644, last_digits_count=4)
4644
回答by Israel Unterman
To get the last 2 digits of num
I would use a 1 line simple hack:
要获得最后 2 位数字,num
我将使用 1 行简单的 hack:
str(num)[-2:]
This would give a string. To get an int, just wrap with int:
这将给出一个字符串。要获得 int,只需用 int 包装:
int(str(num)[-2:])
回答by N0M1N
to get the last 2 digits of an integer.
获取整数的最后 2 位数字。
a = int(input())
print(a % 100)