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

1
  • 2
    Do you actually need a string or a number? Commented Aug 19, 2009 at 15:18

3 Answers 3

9
last_digit = str(number)[-1]
Sign up to request clarification or add additional context in comments.

Comments

8

Use the % operator:

   x = 12 % 10 # returns 2
   y = 25 % 10 # returns 5
   z = abs(-25) % 10 # returns 5

2 Comments

that won't work if the number is negative; Ants' anwer seems better to me
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.
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.