-2

I want to fetch the digit of the last occurance of the substring

input : "abc1  foo barabc2 abc3 abc4 foobar"
output : 4
Psidom
  • 209,562
  • 33
  • 339
  • 356
Rohan Nagalkar
  • 433
  • 2
  • 5
  • 15

2 Answers2

3

You can use re.findall:

import re
s = "abc1  foo barabc2 abc3 abc4 foobar"
print(re.findall('\d+', s)[-1])

Output:

4
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
2

Well if that's the only thing you want to get then I wouldn't use regexp at all, instead:

s = "abc1 foo barabc2 abc3 abc4 foobar"
print([c for c in s if c.isdigit()][-1])

I hope you were looking for something like that.

Szabolcs
  • 3,990
  • 18
  • 38
  • 1
    Wow, that will create a whole list with all the digits and at the end only display the last one. It will work but it will be extremely inefficient (imagine a list of one million elements, all of them digits). If you want to use loops, just reverse iterate until the first digit is found and stop there. –  Feb 06 '18 at 15:40
  • @SembeiNorimaki inefficient compared to what, in what context? Compared it to regular expressions? What if I say, that it's meant to be functional programming instead of imperative style? – Szabolcs Feb 06 '18 at 15:46
  • If your list has thousand million elements and the last element is a digit, reverse looping will only take one operation. You code will first create a new list of up to thousand million elements (in the case all elements are actually digits) and then just displaying the last one. Inefficient compared to this! –  Feb 06 '18 at 15:48
  • @SembeiNorimaki Obviously. But then why not commented on the regexp solutions? And still, efficiency was not a requirement at all here. – Szabolcs Feb 07 '18 at 08:25