Python: handle implicit value in string parsing

More often than not,  we have to handle default/implicit value in string parsing which requires special handling.

Here is an example in Python

Example: a grammar:
<line> ::= { <property> [<separator> <digits>] <separator> }
Example:
computer_id 1 port1 80 port2 88
computer_id 2 port1 port2 8080

By not specifying value, default/implicit value is 80.

   elements.split(" ");
   for i in range(1, len(elements)):
            if i+1 < len(elements) and elements[i+1].isdigit():
               process(elements[i], elements[i+1])    
            else:
               process(elements[i], 80)
Advertisements
Python: handle implicit value in string parsing

First look at Python

I have a chance to play with Python about around Feb 2008 because we have a Python fan. He even wrote some scripts in Python even though we worked on Windows (use Cygwin). I need to modify his scripts to implement my cool Spec-To-Test inititives. There are 2 aspects I like about Python scripts: OOP and whitespace indentation.

And it was the 1st time I’ve seen a language using whitespace indentation as statement block; which means super readability and that mandatory coding standard is always enforced! I could read the guy’s code on the 1st time looking at Python even though I didn’t know Python at that time.

In addition, it was the 1st time I’ve seen an OOP in scripting language; which enabled me to do a lot more. I can see myself become a fan.

First look at Python