简体   繁体   English

字符串中倒数第二个 integer (Python)

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

Second last occurence of an integer in a string integer 在字符串中的倒数第二个出现

Consider "hEY3 a7yY5" as my string, the last integer in this string is 5 and the second last integer is 7.将“hEY3 a7yY5”视为我的字符串,此字符串中的最后一个 integer 是 5,倒数第二个 integer 是 7。

How do I find index of last second integer in this string?如何在此字符串中找到最后一秒 integer 的索引? I'm not sure to if I can use rindex() and if so then how.我不确定我是否可以使用 rindex() 以及如何使用。

The index of 7 in the above string is 6. I can't wrap my head around writing something like stre.rindex(isnumeric())上面字符串中 7 的索引是 6。我无法集中精力编写类似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:如果你不喜欢re那么你可以这样做:

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: 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请注意,如果字符串是“hEY7 a75yY5”,则会打印相同的结果 - 即,这也处理多于一位的序列

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:使用模式获取倒数第二个数字的索引的选项,并使用Match object 的 start() 方法:

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

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

Output Output

6

The pattern matches:模式匹配:

  • \d Match a single digit \d匹配单个数字
  • (?= Positive lookahead, assert what is to the right is (?=正面前瞻,断言右边的是
    • [^\d\n]* Optionally match any char except a digit or a newline [^\d\n]*可选择匹配除数字或换行符之外的任何字符
    • \d Match a single digit \d匹配单个数字
    • [^\d\n]* Optionally match any char except a digit or a newline [^\d\n]*可选择匹配除数字或换行符之外的任何字符
    • \Z End of string \Z字符串结束
  • ) Close the lookahead )关闭前瞻

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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