I have this function which is to give me the last digit of the number passed. Is there a way to get all the digits except the last one?
def lastdigit(num):
out = num%10
return out
I have this function which is to give me the last digit of the number passed. Is there a way to get all the digits except the last one?
def lastdigit(num):
out = num%10
return out
def all_digits_except_last(num):
if abs(num) < 10:
return None # view comment
out = num // 10
return out
This snippet of code integer divides the number by 10 to get all the digits of the number except the last one - then returns it. It also checks if the integer is only one digit - if that is the case it returns None
.
However, you could argue that there is no need to check for a single digit as said below.
Try multiply:
def lastdigit(num):
return int(num*0.1)
print(lastdigit(12355))
Output:
1235
Another approach:
>>> def digits(n):
if n==0: yield 0
while n>0:
yield n%10
n = n/10
>>> n = 123456
>>> all_digits_except_last = [d for d in digits(n)][1:]
>>> all_digits_except_last
[5, 4, 3, 2, 1]
you can use slicing for this. like:-
def except_last_digit(num):
convert_to_str = str(num)
length_of_str = len(convert_to_str)
except_last_digit =
convert_to_str[0:length_of_str-1]
convert_to_int = int(except_last_digit)
return convert_to_int
Handling digits is better done by casting your integer to a string.
def firstdigits(num):
return str(num)[:-1]
firstdigits(121) # '12'