简体   繁体   中英

Second last occurence of an integer in a string (Python)

Second last occurence of an integer in a string

Consider "hEY3 a7yY5" as my string, the last integer in this string is 5 and the second last integer is 7.

How do I find index of last second integer in this string? I'm not sure to if I can use rindex() and if so then how.

The index of 7 in the above string is 6. I can't wrap my head around writing something like stre.rindex(isnumeric())

This will find the penultimate occurrence of a sequence of digits in a string and print its offset.

import re
a = "hEY3 a7yY5"
offsets = [m.start() for m in re.finditer(r'\d+', a)]
print(-1 if len(offsets) < 2 else offsets[-2])

If you are averse to re then you can do it like this:

offsets = []

for i, c in enumerate(a):
    if c.isdigit():
        if offsets:
            if offsets[-1] != i - 1:
                offsets.append(i)
        else:
            offsets = [i]
            
print(-1 if len(offsets) < 2 else offsets[-2])

Output:

6

Note that the same result would be printed if the string is "hEY7 a75yY5" - ie, this also handles sequences of more than one digit

You may try something like this

a = "hEY3 a7yy5"
out = [i for i,j in enumerate(a) if j.isnumeric()][-2]
print(out)

An option to get the index of the second last digit using a pattern, and use the start() method of the Match object:

s = "hEY3 a7yY5"
pattern = r"\d(?=[^\d\n]*\d[^\d\n]*\Z)"

m = re.search(pattern, s)
if m:
    print(m.start())

Output

6

The pattern matches:

  • \d Match a single digit
  • (?= Positive lookahead, assert what is to the right is
    • [^\d\n]* Optionally match any char except a digit or a newline
    • \d Match a single digit
    • [^\d\n]* Optionally match any char except a digit or a newline
    • \Z End of string
  • ) Close the lookahead

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