How to in Python

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Dec 19 13:10:59 EST 2007


En Wed, 19 Dec 2007 14:02:00 -0300, <MartinRinehart at gmail.com> escribi�:

> I've got a pointer to a position in a line of code that contains
> either a digit or a period (decimal point). I've got this comment:
>
>             Numbers are one of these:
>                 integers:
>                     digit+
>                     0xhex_digit+
>                 decimals:
>                     digit+.digit*[E['+'|'-']digit+]
>                     .digit+[E['+'|'-']digit+]
>                     digit+[.digit*]%
>                     .digit+%
>
> Common metacode: '*' = 0 or more, '+' = 1 or more, [] = optional, | =
> or, ...
>
> Now I need to instantiate the comment. How would an experienced Python
> coder proceed?

Do you have to validate input based on that grammar? That is, do you want  
a function like this?

def is_valid_number(input):
   if ....
      return True
   return False

Or, do you want to consume characters starting from your pointer, stopping  
when an invalid character appears?

This looks like one of those few cases where "Use a regular expression"  
may be a good answer. If you like a more Pythonic approach, try using  
Pyparsing <http://pyparsing.wikispaces.com/>

-- 
Gabriel Genellina




More information about the Python-list mailing list