Code works fine alone, but in function shows error

1.8k views Asked by At

I have problem with code. I have written a function for extracting a parameter, by sending the original string, and pre/post text fragments as well as the number of occurance in text. When I wrote it in simple code it worked great:

searchstr = 'qwer1234asdfqwer5678asdfqwer1234asdfqwer5678asdf'
startstr = 'qwer'
endstr = 'asdf'
occurancenr = 4
start = searchstr.find(startstr)
print 'start = ' + str(start)
while start >= 0 and occurancenr > 1:
  start = searchstr.find(startstr, start + len(startstr))
  occurancenr -= 1
  print 'start = ' + str(start) + ', and nr = ' + str(occurancenr)
start = start + len(startstr)
end = searchstr.index( endstr, start )
print 'result = ' + searchstr[start:end]

But when I put it in method that returns the string I get error:

Heres the function:

  def findparam (self, searchstr, startstr, endstr, occurancenr):
  start = searchstr.find(startstr)
  while start >= 0 and occurancenr > 1:
    start = searchstr.find(startstr, start + len(startstr))
    occurancenr -= 1
  start = start + len(startstr)
  end = searchstr.index( endstr, start )
  return 'result = ' + searchstr[start:end]

and here is the call for it:

abc = 'qwer1234asdfqwer5678asdf'
aa = 'qwer'
bb = 'asdf'
print self.findparam(abc, aa, bb, 1)

The error looks like this:

SyntaxError: ('invalid syntax', ('C:\\grinder-3.4\\scripts\\ResultCheckMerged.py', 367, 3, '  start = searchstr.find(startstr)'))
(no code object) at line 0

Technically this is a function for grinder script running and the comparator uses jython, but, since no java code is used and its just python code, I consider this a python problem. But still, maybe it has something to do with this.

Any tips on this appreciated!

2

There are 2 answers

0
Roman Bodnarchuk On BEST ANSWER

You just need to indent you code properly. The next should work:

  def findparam (self, searchstr, startstr, endstr, occurancenr):
    start = searchstr.find(startstr)
    while start >= 0 and occurancenr > 1:
      ...
0
steller On

do not indent def line.


def findparam (self, searchstr, startstr, endstr, occurancenr):
      start = searchstr.find(startstr)
      while start >= 0 and occurancenr > 1:
        start = searchstr.find(startstr, start + len(startstr))
        occurancenr -= 1
      start = start + len(startstr)
      end = searchstr.index( endstr, start )
      return 'result = ' + searchstr[start:end]