简体   繁体   中英

Python find position of last digit in string

I have a string of characters with no specific pattern. I have to look for some specific words and then extract some information. Currently I am stuck at finding the position of the last number in a string.

So, for example if:

mystring="The total income from company xy was 12320 for the last year and 11932 in the previous year"

I want to find out the position of the last number in this string. So the result should be "2" in position "70".

You can do this with a regular expression, here's a quick attempt:

>>>mo = re.match('.+([0-9])[^0-9]*$', mystring)
>>>print mo.group(1), mo.start(1)
2 69

This is a 0-based position, of course.

You can use a generator expression to loop over the enumerate from trailing within a next function:

>>> next(i for i,j in list(enumerate(mystring,1))[::-1] if j.isdigit())
70

Or using regex :

>>> import re
>>> 
>>> m=re.search(r'(\d)[^\d]*$',mystring)
>>> m.start()+1
70

Save all the digits from the string in an array and pop the last one out of it.

array = [int(s) for s in mystring.split() if s.isdigit()]
lastdigit = array.pop()

It is faster than a regex approach and looks more readable than it.

def find_last(s):
    temp = list(enumerate(s))
    temp.reverse()
    for pos, chr in temp:
        try:
            return(pos, int(chr))
        except ValueError:
            continue

You could reverse the string and get the first match with a simple regex:

s = mystring[::-1]
m = re.search('\d', s)
pos = len(s) - m.start(0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM