pythonstrtod

Python equivalent to C strtod


I am working on converting parts of a C++ program to Python, but I have some trouble replacing the C function strtod. The strings I'm working on consists of simple mathmatical-ish equations, such as "KM/1000.0". The problem is that the both constants and numbers are mixed and I'm therefore unable to use float().

How can a Python function be written to simulate strtod which returns both the converted number and the position of the next character?


Solution

  • I'm not aware of any existing functions that would do that.

    However, it's pretty easy to write one using regular expressions:

    import re
    
    # returns (float,endpos)
    def strtod(s, pos):
      m = re.match(r'[+-]?\d*[.]?\d*(?:[eE][+-]?\d+)?', s[pos:])
      if m.group(0) == '': raise ValueError('bad float: %s' % s[pos:])
      return float(m.group(0)), pos + m.end()
    
    print strtod('(a+2.0)/1e-1', 3)
    print strtod('(a+2.0)/1e-1', 8)
    

    A better overall approach might be to build a lexical scanner that would tokenize the expression first, and then work with a sequence of tokens rather than directly with the string (or indeed go the whole hog and build a yacc-style parser).