1

I need to be able to get the last digit of a number.

i.e., I need 2 to be returned from: 12.

Like this in PHP: $minute = substr(date('i'), -1) but I need this in Python.

Any ideas

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Adam Chetnik
  • 1,906
  • 5
  • 27
  • 38

3 Answers3

9
last_digit = str(number)[-1]
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Ants Aasma
  • 53,288
  • 15
  • 90
  • 97
8

Use the % operator:

   x = 12 % 10 # returns 2
   y = 25 % 10 # returns 5
   z = abs(-25) % 10 # returns 5
João Silva
  • 89,303
  • 29
  • 152
  • 158
  • 1
    that won't work if the number is negative; Ants' anwer seems better to me – redtuna Aug 19 '09 at 15:18
  • 1
    The PHP example code seems to imply the OP is dealing with minute-of-hour numbers. In this case we are talking non-negative integers and modulo seems quite reasonable. – bobince Aug 19 '09 at 15:27
2

Python distinguishes between strings and numbers (and actually also between numbers of different kinds, i.e., int vs float) so the best solution depends on what type you start with (str or int?) and what type you want as a result (ditto).

Int to int: abs(x) % 10

Int to str: str(x)[-1]

Str to int: int(x[-1])

Str to str: x[-1]

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395