user3765030
user3765030

Reputation: 363

How to find the last non-digit in a string using python3

I use:

a_string = '00:00:02'
for char in reversed(a_string):
    if not char.isdigit():
        break

and "char" will be the last non-digit, but it feels hackish. Is there a more elegant way?

Upvotes: 1

Views: 529

Answers (1)

Jongware
Jongware

Reputation: 22457

Apart from a dedicated function? Pick any:

# regex
print (re.findall(r'(\D)\d*$', a_string)[0])

# list comprehension
print ([x for x in a_string if not x.isdigit()][-1])

# filter
print ([x for x in filter(lambda x: not x.isdigit(), a_string)][-1])

Upvotes: 1

Related Questions