Reputation: 11
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
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
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
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
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