Python - substr

旧街凉风 提交于 2020-01-05 04:40:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!