How to check last digit of number

前端 未结 8 1917
情歌与酒
情歌与酒 2020-12-06 04:21

Is there a way to get the last digit of a number. I am trying to find variables that end with \"1\" like 1,11,21,31,41,etc..

If I use a text variable I can simply pu

8条回答
  •  一向
    一向 (楼主)
    2020-12-06 04:46

    So you want to access the digits in a integer like elements in a list; easiest way I can think of is:

    n = 56789
    lastdigit = int(repr(n)[-1])
    # >  9
    

    Convert n into a string, accessing last element then use int constructor to convert back into integer.

    For a Floating point number:

    n = 179.123
    fstr = repr(n)
    signif_digits, fract_digits = fstr.split('.')
    # >  ['179', '123']
    signif_lastdigit = int(signif_digits[-1])
    # >  9
    

提交回复
热议问题