Puff
Puff

Reputation: 515

Get digits at end of string in a pythonic way

I'm using python 3.x. I'm trying to get the (int) number at the end of a string with format

string_example_1 = l-45-98-567-567-12
string_example_2 = s-89-657

or in general, a single lowercase letter followed by a number of integers separated by '-'. What I need is to get the last number (12 and 657 in these cases). I have archived this with the function

def ending(the_string):
    out = ''
    while the_string[-1].isdigit():
        out = the_string[-1] + out
        the_string = the_string[:-1]
    return out

but I'm sure there must be a more pythonic way to do this. In a previous instance I check manually that the string starts the way I like by doing something like

if st[0].isalpha() and st[1]=='-' and st[2].isdigit():
    statement...

Upvotes: 1

Views: 61

Answers (2)

Patrick Haugh
Patrick Haugh

Reputation: 60984

I would just split the string on -, take the last of the splits and convert it to an integer.

string_example_1 = "l-45-98-567-567-12"
string_example_2 = "s-89-657"

def last_number(s):
    return int(s.split("-")[-1])

print(last_number(string_example_1))
# 12
print(last_number(string_example_2))
# 657

Upvotes: 3

erip
erip

Reputation: 16935

Without regular expressions, you could reverse the string, take elements from the string while they're still numbers, and then reverse the result. In Python:

from itertools import takewhile

def extract_final_digits(s):
    return int(''.join(reversed(list(takewhile(lambda c: c.isdigit(), reversed(s))))))

But the simplest is to just split on a delimiter and take the final element in the split list.

Upvotes: 1

Related Questions