tags:

views:

756

answers:

3

Hi

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

+8  A: 
last_digit = str(number)[-1]
Ants Aasma
+8  A: 

Use the % operator:

   x = 12 % 10 # returns 2
   y = 25 % 10 # returns 5
   z = abs(-25) % 10 # returns 5
JG
that won't work if the number is negative; Ants' anwer seems better to me
redtuna
Fixed, using `abs`.
JG
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
+2  A: 

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