1

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
Nicole Foster
  • 381
  • 4
  • 14

6 Answers6

2
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.

RealPawPaw
  • 988
  • 5
  • 9
1

Try multiply:

def lastdigit(num):
    return int(num*0.1)
print(lastdigit(12355))

Output:

1235
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

Why not just

def not_last(x):
    return x // 10
0

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]
mshsayem
  • 17,557
  • 11
  • 61
  • 69
0

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
0

Handling digits is better done by casting your integer to a string.

def firstdigits(num):
    return str(num)[:-1]

firstdigits(121) # '12'
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73