简体   繁体   中英

Last 2 digits of an integer? Python 3

With my code, I want to get the last two digits of an integer. But when I make xa positive number, it will take the first x digits, if it is a negative number, it will remove the first x digits.

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)

Why don't you extract the absolute value of the number modulus 100? That is, use

 abs(num) % 100 

to extract the last two digits?

In terms of performance and clarity, this method is hard to beat.

To get the last 2 digits of num I would use a 1 line simple hack:

str(num)[-2:]

This would give a string. To get an int, just wrap with int:

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

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:

# 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:

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

to get the last 2 digits of an integer.

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

You can try this:

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

abs(num) % 100 would not work to get 00 from a number such as 900

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM