Last 2 digits of an integer? Python 3

前端 未结 4 942
不思量自难忘°
不思量自难忘° 2020-12-07 00:56

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 remo

4条回答
  •  不思量自难忘°
    2020-12-07 01:54

    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
    

提交回复
热议问题