整数的最后 2 位数字? Python 3

问题描述 投票:0回答:6

通过我的代码,我想获取整数的最后两位数字。但是当我将x设置为正数时,它将取前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)
python python-3.x integer
6个回答
49
投票

为什么不提取模100的绝对值呢?也就是说,使用

 abs(num) % 100 

提取最后两位数字?

就性能和清晰度而言,这种方法很难被击败。


16
投票

要获取

num
的最后 2 位数字,我将使用 1 行简单的 hack:

str(num)[-2:]

这将给出一个字符串。 要获取 int,只需用 int 包裹即可:

int(str(num)[-2:])

6
投票

提取数字最后两位数字的更简单方法(效率较低)是将数字转换为

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`

或者,您可以通过使用模

%
运算符(更高效)来实现它,(要了解更多信息,请检查%在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

3
投票

获取整数的最后 2 位数字。

a = int(input())
print(a % 100)

1
投票

你可以试试这个:

浮动(str(num)[-2:])


0
投票

我会使用正则表达式,因为我可以:)

import re

x = re.sub(r"^\d{2}(\d{2})$", r"\1", str(num))
assert len(str(x)) == 2

如果输入的不是4位数字,则返回原来的内容。 也许断言可能会有所不同。 我喜欢这个的另一个原因是,如果

num
已经减少到 2 个字符,它就会留下它。

© www.soinside.com 2019 - 2024. All rights reserved.