views:

149

answers:

2

I am looking to se if this code can be optimized.

def gB(a,b,c):  
    x=len(b)  
    d=a.find(b)+x  
    e=a.find(c,d)  
    return a[d:e]  

print gB("abc","a","c")
+4  A: 

There's a couple of problems with your code that you probably should fix before trying to optimize it.

Firstly, it's undocumented and the naming is not helpful. I assume it is trying to extract a string between start and end markers.

Secondly, it gives an apparent match even if the start and/or end markers aren't found:

>>> print gB("abc", "d", "e")
ab

It would be much better to raise an exception or return None in this case.

As for the speed, I doubt you can get faster for finding strings than using the builtin string finding functions. They are written in C and no doubt had a lot of time spent optimizing them. If someone can implement string finding faster in Python then the people who wrote find need to go back and look at their code again.

Mark Byers
+1  A: 

What about this?

import re

def gB(a, b, c):
    return (re.findall('%s(.*?)%s' % (b, c), a) or [''])[0]

If you are talking about smaller code, I think the re module can help you.

Cacilhas
You need to re.escape b and c if this is going to work for b = '.' for example.
Mark Byers
I don't think you'd want to use `findall()`, only to discard all but the first match.
Peter Hansen