Search code examples
pythonstringscientific-notation

Extracting scientific notation from a string


I am trying to extract scientific notation from strings like:

`#DataCGSConversionFactor[0] = 1.0051900924519e-29`

Unfortunately because of the first 0 that isn't a part of the number I want, the other solutions I have tried don't work, giving:

ValueError: invalid literal for float(): 0]

Thanks in advance.


Solution

  • For the string you show,

    x = "#DataCGSConversionFactor[0] = 1.0051900924519e-29"
    
    f = float(x.split()[-1])    # split at spaces, take last item, and cast to a float
    
    print f, type(f)
    # 1.0051900924519e-29, float