1

I am trying to write a basic interpreter in python. So, I am at that point where I am trying to declare whether a string entered in command prompt is a method or variable type.

So not trying any fancy stuff..

s="12345" #variable
s ="foo()" method
s = "foo(1234)" method

What is a robust way to do this (for example.. robust for whitespaces ... throw error if syntax is not proper)

My code is pretty straightforward

s = s.strip()

params=   s[s.find("(") + 1:s.find(")")] # find the params..

The above command works in case two and case three but for case 1.. it gives weird results..

7
  • What do you expect params to be for '12345'? Commented Feb 9, 2013 at 23:05
  • @Volatility: yes.. or nothing in case of 1st and 2nd case Commented Feb 9, 2013 at 23:06
  • 2
    A robust way is to write an actual parser, using something like ANTLR or pyparsing or whatever comes up under "python parser library". Commented Feb 9, 2013 at 23:16
  • 1
    the reason why you get the funny result in the first case is because your statement in case of s = 123456 s[s.find("(") + 1:s.find(")")] produces s[-1 + 1 : -1 ] s[0 : -1 ] so you always miss the last character Commented Feb 9, 2013 at 23:18
  • 1
    Instead of parsing the string directly, you should first break it up into tokens, i.e. strings, bracket, numbers, operators, etc. Then, parse the sequence of tokens. Commented Feb 9, 2013 at 23:41

1 Answer 1

1

For the scenarios you are asked for i think this could do the trick

have a go

s[ 1+s.find("(") if s.find("(") > 0 else None : -1 if s.find(")") > 0 else None]

edit: making a bit neater as suggested by Paul:

s[ 1+s.find("(") if '(' in s else None : -1 if ')' in s  else None]
Sign up to request clarification or add additional context in comments.

2 Comments

I think this would be clearer if it weren't crammed on to one line.
I think this would also be clearer if you used the more up-to-date idiom of if '(' in s instead of if s.find('(') > 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.