Jason
Jason

Reputation: 11

Python - Function to find last number

I'm trying to create a function that returns the very last digit in a python string and if there are no digits in the string, it simply returns -5 as a result. This is what i've gotten but it returns 0 if the string is made up of no digits or if the final character in the string is not a digit. For example, LastNum("1*2*3*") should return 3, LastNum("****") should return -5. Help is greatly appreciated.

def LastNum(st):
    Result = 0
    for i in (st):
        if i.isdigit():
            Result = Result + int(max(st[-1::]))
    return Result

Upvotes: 0

Views: 697

Answers (4)

C. Feenstra
C. Feenstra

Reputation: 593

A nice one-liner (probably not the most readable way to do it though)

import re

def LastNum(st, default=-5):
    return int((re.findall(r'\d', st) or [default])[-1])

Upvotes: 0

Mahesh Karia
Mahesh Karia

Reputation: 2055

You can use regex as follows too.

import re

def LastNum(st):
    result = -5
    regex_res = re.findall('\d+', st)
    if regex_res:
        result = regex_res[-1]
    return result

print LastNum("1*2*3*")

output:

3

Upvotes: 0

Sagun Shrestha
Sagun Shrestha

Reputation: 1198

It would be a good idea to start searching from the reverse

def lastNum(st):
    # st[::-1] is reverse of st
    for s in st[::-1]:
        if s.isdigit():
            return int(s)

    return -5

Upvotes: 3

Julien
Julien

Reputation: 15071

I don't understand the intended logic behind your code, but this simpler one should work:

def LastNum(st):
    Result = -5
    for i in st:
        if i.isdigit():
            Result = int(i)
    return Result

Upvotes: 0

Related Questions