Search code examples
pythoncall

How to callthe first float in a list in Python


In Python if I have numerous lines of data containing both strings and floats (sample below) which I have tokenized, how can I call the first float value in each line if this position is not constant? I eventually want to use this as a reference point for latter tokens. Thanks in advance.

F + FR > FR* + F + E 11.60 0 2 FR > FR*

F + FR > FR*** + F 11.60 0 2382 FR > FR***


Solution

  • You can use the re module. Just import it and look for digits with a . within them. For example,

    import re
    def findFloat(s): 
        return float( re.search('[0-9]+.[0-9]+', s).group() )
    

    This finds the first occurrence of a group of numbers separated by a .