问题
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:
last_digit = str(number)[-1]
回答2:
Use the % operator:
x = 12 % 10 # returns 2
y = 25 % 10 # returns 5
z = abs(-25) % 10 # returns 5
回答3:
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]
来源:https://stackoverflow.com/questions/1300610/python-substr