[英]Last 2 digits of an integer? Python 3
使用我的代码,我想获取 integer 的最后两位数字。 但是当我做 xa 正数时,它将取前 x 位,如果是负数,它将删除前 x 位。
代码:
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)
你为什么不提取数模100的绝对值? 也就是说,使用
abs(num) % 100
提取最后两位数字?
在性能和清晰度方面,这种方法很难被击败。
要获得num
的最后 2 位数字,我将使用 1 行简单的 hack:
str(num)[-2:]
这将给出一个字符串。 要获得 int,只需用 int 包装:
int(str(num)[-2:])
提取数字最后两位数字的更简单方法(效率较低)是将数字转换为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`
或者,您可以通过使用 modulo %
运算符(更有效)来实现它,(要了解更多信息,请查看% 在 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
示例运行:
>>> get_last_digits(95432)
32
>>> get_last_digits(2)
2
>>> get_last_digits(34644, last_digits_count=4)
4644
获取整数的最后 2 位数字。
a = int(input())
print(a % 100)
你可以试试这个:
浮点数(str(num)[-2:])
abs(num) % 100 无法从诸如 900 之类的数字中获取 00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.