-2

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

input : "abc1  foo barabc2 abc3 abc4 foobar"
output : 4
Psidom
  • 195,464
  • 25
  • 298
  • 322
Rohan Nagalkar
  • 365
  • 2
  • 3
  • 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
  • 66,333
  • 7
  • 57
  • 95
1

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,730
  • 14
  • 34
  • 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. – Sembei Norimaki 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! – Sembei Norimaki 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